brunch

You can make anything
by writing

C.S.Lewis

by Tilltue Oct 09. 2016

Firebase, #iOS 클라우드메시지

FCM, iOS, Firebase Cloud Messaging

* 이글은 Swift 3.0 , Firebase 3.6.0 를 기준으로 작성되었습니다.


firebase 에서는 무료로 push 서비스를 지원하고 있다.

firebase cloud messaging(FCM) 이 그것인데 타겟을 다양한 형태로 구분해서 보낼 수 잇기 때문에, 활용도가 높다

예를들어, 특정 앱 버전, 특정 사용자 그룹, 특정 OS 버전. 등등으로 나누어서 보낼수 있다.

 이번 포스팅에서는 iOS 에서 어떻게 FCM을 연동하는지에 대한 기초과정에 대한 설명을 하려 한다.



push 서비스를 위해서는 apn ssl 인증서가 필요하다.

https://firebase.google.com/docs/cloud-messaging/ios/certs

를 통해 인증서를 생성하고 firebase 에 등록한다.


이제 XCode 프로젝트로 돌아오자.


Podfile 에 FCM을 추가하고 pod install 을 통해 설치하자

pod 'Firebase/Messaging'


UserNotifiations.framework 를 추가하자

push 서비스를 활성화했는지 확인


아래의 과정은 모두 AppDelegate.swift 에서 수행한다.

import UserNotifications

import Firebase

import FirebaseInstanceID

import FirebaseMessaging

위와 같이 추가


이제 앱이 foreground 일때 push 알림을 받으면 확인이 가능하도록 로직을 추가

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("%@", userInfo)
    }


FCM 을 사용하려면 앱이 FCM에 연결되어야 한다.

아래의 로직을 추가. connectToFcm ( 토큰이 갱신될때 연결을 하도록 구성 )

@objc fileprivate func tokenRefreshNotificaiton(notification: NSNotification) {
        let refreshedToken = FIRInstanceID.instanceID().token()!        
        print("InstanceID token: \(refreshedToken)")        
        connectToFcm()    
}

func connectToFcm() {
  FIRMessaging.messaging().connectWithCompletion { (error) in
    if (error != nil) {
      print("Unable to connect with FCM. \(error)")
    } else {
      print("Connected to FCM.")
    }
  }
}

앱이 백그라운드 상태가 되면 FCM 연결을 끊도록 구성하자.

func applicationDidEnterBackground(_ application: UIApplication) {                firebaseDisconnect()
}

fileprivate func firebaseDisconnect(){
        FIRMessaging.messaging().disconnect()
}

apns 토큰을 FCM 등록 토큰과 매핑하기위해 아래의 함수를 추가한다.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .sandbox)
    }


firebase 의 가이드는 여기까지. 실행을 해보자.

<FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(full)"

위와 같은 에러가 발생.


info.plist 에 위와같이 추가

Required background modes ... <- 이부분

FirebaseAppDelegateProxyEnabled 는 파이어 베이스 내부 로그를 끄는 것이니 필요에 따라 추가


아래의 과정을 추가.

NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
                if granted == true{
                    print("Allow")                    
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Don't Allow")
                }
            }

        } else {
            // Fallback on earlier version
        }

NotificationCenter에서 NSNotification.Name.firInstanceIDTokenRefresh 이벤트를 받을 받을 함수로 위에서 선언한 tokenRefreshNotificaiton 를 등록하자.

iOS 10 에서는 push 알림에 대한 승인을 받는 코드를 직접 입력하는 것으로 보인다.

위와 같이 iOS 10 에서 승인을 받는 코드를 넣어준다. 위 과정은 didFinishLaunchingWithOptions 함수 에서 이루어 지도록 한다.


이제 앱을 실행하면 push 알림에 대한 승인을 물어보게 된다.

승인을 하고 테스트 메시지를 발송해보자

firebase console 에서 아래의 화면에서 앱 선택을 한뒤 보내보자.


등록된 모바일 기기에서 push 가 오는 것을 확인 할 수 있다.


매거진의 이전글 Firebase #iOS,데이터베이스 이벤트

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari