애플의 기존 APNS와 비교해서 Firebase p8 인증키를 사용하면 인증서 재발급이 필요없고 개발과 운영 구분없이 푸시를 받을 수 있다는 장점이 있다?
참고로 한 계정 내에 앱이 여러개가 있어도 동일한 하나의 apns 키를 적용해주면 된다.
참고 : StackOverflow - Single APNs key on multiple applications
Firebase 생성 및 앱 추가는 이미 다 되어 있는 상태.
AppDelegate에 import Firebase
<프로젝트 TARGETS>
Targets - Signing & Capabilities 들어가서
+Capability 누르고 Push Notifications, Background Modes 추가해준다
Background Modes 에서 Remote notifications 체크 해주기.
<Podfile>
pod ‘Firebase/Messaging’ 추가 후
터미널에서 pod install
<AppDelegate>
import Firebase 해주고 AppDelegate 클래스 안에 Firebase와 UserNotification 기본 세팅을 해준다.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions,completionHandler: {_, _ in })
application.registerForRemoteNotifications()
return true
}
옵션에 .badge는 앱 아이콘 위에 뜨는 빨간색 알림 숫자?
UNUserNotificationCenter가 바로 앱의 모든 notification-related 동작들을 관리하는 책임자.
extension으로 UNUserNotificationCenterDelegate와 MessagingDelegate 추가해주고
// Device Token Success
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(fcmToken!)")
let dataDict:[String: String] = ["token": fcmToken!]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//let 000 = notification.request.000
//이렇게 필요한 정보 request 해서 받아오고, 푸시 받으면
completionHandler([.alert, .sound])
}
클라우드 메시징 기능에 들어가보면
push 가 잘 들어오는지 간단히 테스트 해볼 수도 있다.
클라우드 메시징 알림 작성 하면
이렇게 제목이랑 텍스트 설정해주고
테스트 메시지 전송을 누른다. (특정 기기에서 테스트하고 싶은 거면 다음으로는 안가도됨)
기기에서 테스트 창이 뜨면 FCM 등록 토큰 추가 란에
위 코드를 실행하면 콘솔 창에 뜨는 fcmToken 값을 복사해서 넣어주고 테스트를 하면 해당 기기로 푸시 알림이 온다.
신기신기!!
참고 : github/ClintJang
'초보 iOS 개발자의 일상 > 개발 업무' 카테고리의 다른 글
Universal Links 이용한 웹에서 앱 및 앱스토어 이동 (0) | 2021.04.19 |
---|---|
[Swift iOS, JavaScript] url schemes 사용하여 웹에서 앱 호출 및 앱스토어 연결하기 (10) | 2021.04.16 |
[Swift iOS] WKUserContentController 하이브리드 앱 웹 뷰 연동하기 (0) | 2021.04.14 |
앱 심사를 통과하지 못함. 사유 안뜰 때! 심사 거부 사유 확인하는 법 (0) | 2021.04.12 |
6년 된 Object-C 프로젝트 수정 요청 (0) | 2021.04.07 |