[iOS] Push Notification 처리하기

kimdocs...📄·2021년 3월 27일

https://firebase.google.com/docs/cloud-messaging/ios/client?hl=ko
👆파이어베이스 문서를 참고하여 사용 준비를 해줍니다.

푸시알림을 핸들링하기 위해 고려해야 할 상황은 4가지입니다.

1) 앱이 종료되어 있는 경우
2) 앱이 실행 중인 경우
3) 앱이 백그라운드인 경우
4) 사용자가 푸시 알림을 클릭한 경우

✔️ 앱이 종료되어 있는 경우

👉 didFinishLaunchingWithOptions

func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        if (launchOptions?[.remoteNotification]) != nil {
        //여기서 처리
        }
}

✔️ 앱이 실행 중인 경우

👉 willPresent

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              willPresent notification: UNNotification,
    			      withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    print(userInfo)
   //여기서 처리
    completionHandler([[.alert, .sound]])
  }

✔️ 백그라운드인 경우 & 사용자가 푸시를 클릭한 경우

👉 didReceive

func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    print(userInfo)
	//여기서 처리
    completionHandler()
  }

여기에도 위와 같은 함수들이 잘 나와있으니 참고해보세요 :)

단,애플 공식 문서를 살펴보면,

Deprecated
Use userNotificationCenter(_:willPresent:withCompletionHandler:) instead.

fetchCompletionHandler 가 없는 application(_:didReceiveRemoteNotification:)는 Deprecated 되었으므로 사용을 안하는 것을 추천드립니다. (사실 willPresent를 이용하면 되기 때문에 굳이 사용할 필요는 없어보여요)

앱의 실행 상태에따라 처리하는 법은 여기를 참고해주세용 >.<

profile
👩‍🌾 GitHub: ezidayzi / 📂 Contact: ezidayzi@gmail.com

0개의 댓글