Firebase를 이용해 원격 푸시 알림을 사용해봅니다.
Push Notification(1), Push Notification(2)에
PushNotification과 APNs의 내용들을 자세히 정리했기 때문에 추가적인 설명은 넘어가겠습니다.
1. APNs 인증 키를 발급받아야합니다.
Apple Developer > 인증서, 식별자 및 프로파일 > 키
키는 계정당 2개가 최대입니다.
키 이름은 원하는대로 생성하고, Apple Push Notifications 를 체크합니다.
Continue를 클릭합니다.
Register를 선택하고
등록을 완료하면 "Download Your Key" 페이지가 등장하는데,
여기서 우측에 DownLoad버튼을 클릭하면 ".p8" 확장자의 파일이 다운로드됩니다.
여기서 p8파일을 다운로드하고 KeyID를 꼭 메모해놓습니다.
* 한번 다운로드 이후 재시도 불가능 합니다
여기서 p8파일은 APNs를 사용하기위해 Apple에서 제공하는 인증서입니다.
APNs로 푸시 알림을 보낼 때 요청을 인증하는데 사용됩니다.
이제 Identifier로 이동합니다.
App IDs를 클릭하고 Continue를 선택합니다.
Description을 입력하고 Bundle ID를 입력합니다.
BundleID는 FCM을 사용할 프로젝트에서 찾을 수 있습니다.
그리고 PushNotification을 체크합니다.
하고 Continue.. 쭉쭉 진행하면 됩니다.
2. Firebase 프로젝트 생성, 앱 연동
이제 FireBase를 연동해야합니다.
프로젝트를 생성합니다.
프로젝트 이름은 XCode프로젝트 이름과 상관없습니다.
그리고 진행하면 Firebase가 추가되고면 iOS앱을 등록해줍니다.
Apple 번들 ID는 위에 사용했던 XCode Project의 BundleID입니다.
이제 XCode프로젝트에 GoogleService-Info.plist파일을 추가해줍니다.
다운로드 받은 파일을 해당 프로젝트 폴더로 옮기고,
XCode에서 같은 Target내에 드래그해서 넣어줍니다.
이제 Firebase pod을 설치해줍니다.
단순히 Push Notification만 사용해보고싶은경우 Firebase/Messaging만 추가해주면 됩니다.
3. 인증서 추가
Firebase 콘솔에서 생성한 프로젝트 > 톱니바퀴 > 클라우드메시징으로 진입합니다.
아래로 내리면 APN인증키부분이 있습니다.
"Download Your Key" 페이지에서 다운로드한 .p8파일을 업로드합니다.
키 ID는 "Download Your Key" 페이지에서 메모한 KeyID이며
팀 ID는 여기에서 로그인하고 아래로 내리면 확인할 수 있습니다.
4. XCode Project 설정
iOS 프로젝트에서 PushNotification 설정을 해야합니다.
2가지를 할건데 Background Modes, Push Notification을 추가해줍니다.
이 화면에서 +버튼을 클릭합니다.
총 두가지를 추가해줍니다.
Background Modes에서 Remote Notifications를 체크해줍니다. 체크 후 바로 해제된다면 시뮬레이터를 종료하고 체크해줍니다.
AppDelegate에 코드를 추가해줍니다.
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
let notificationCenter = UNUserNotificationCenter.current()
let notificationOption: UNAuthorizationOptions = [.alert, .badge, .sound]
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
Messaging.messaging().delegate = self
notificationCenter.delegate = self
registerForPushNotivications()
// apns토큰 요청
application.registerForRemoteNotifications()
return true
}
// notification 권한 요청
func registerForPushNotivications() {
notificationCenter.requestAuthorization(
options: notificationOption, completionHandler: { granted, error in
if let error = error {
print("DEBUG: \(error)")
}
if granted {
print("권한 허용 여부 \(granted)")
}
}
)
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// 토큰이 성공적으로 도착하면 호출
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
// foregound 모드에서도 Push를 받을 수 있게
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound, .banner])
}
}
extension AppDelegate: MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("FCM Token: \(fcmToken)")
}
}
앱을 실행하면 콘솔로 디바이스 토큰이 도착하게됩니다.
디바이스토큰은 알림을 받을 Device의 주소가 됩니다.
PushNotification(1)의 글에 자세히 설명하고있습니다.
"" 따옴표 안의 디바이스토큰을 복사합니다.
5. 테스트 진행
Cloud Messaging으로 접속해줍니다.
여기서 첫 번째 캠페인 만들기를 클릭하고,
제목과 텍스트를 작성하고
우측 기기 미리보기의 테스트메시지 전송을 클릭합니다.
여기에서 아까 복사해놓은 Device Token을 입력하고 테스트를 눌러봅니다.
도착 끝 !