conyang's iOS

[iOS] Push Notification 메소드 정리 본문

iOS

[iOS] Push Notification 메소드 정리

conyang 2024. 3. 15. 00:10

1. UserInfo


  • 푸시 데이터가 담겨있는 저장소, [ AnyHashable : Any ]? 형태의 자료형입니다.
{
	"aps": {
    	"alert": "test"
        "badge": "1"
    }
}

 

 

2.  Push Notification 메소드 정리


1) 앱이 실행 중인 경우 (Foreground)

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

 

 

 

2) 앱이 백그라운드인 경우 (Background) & 사용자가 푸시를 탭한 경우

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

 

 

 

3) 앱이 종료되어 있는 경우 (Terminated)

  • application(_:didFinishLaunchingWithOptions:)
 func application (_ application: UIApplication, 
 			didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      let userInfo = (launchOptions?[.remoteNotification] as? [String: Any])
      print(userInfo)
      // 여기서 UserInfo와 DeepLink 처리
 }

 

 

 

4) 앱이 종료되어 있을 때 (Terminated) 푸시를 탭한 경우

  • application(_:didReceiveRemoteNotification:)
// 앱이 종료되었을 때 시스템 노티를 탭한 경우 이곳에서도 수신
func application(_ application: UIApplication, 
		didReceiveRemoteNotification userInfo: [AnyHashable: Any], 
        	fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("앱 종료 후 알림 클릭")
    print(userInfo)
 }