Search code examples
iosswiftpush-notificationappdelegate

How to debug remote push notification when app is not running and tap push notification?


When app is running and it receive push notification then didReceive is called.

func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    )

So when above delegate is called then i present a screen using the payload i receive. There is no problem here.

When app is not running and user tap the notification then it should present the same screen like above. It's not working because i didn't added a code in didFinishLaunchingWithOptions.

So, then i added the following code -

func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        
         ......        
    
            
        if let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
         ......
        }
        
        return true
    }

But this is not working and i cannot debug because when in debug mode i have to kill the app from background and tap the notification but in this case the debugger won't work. I tried alternative method i.e. showing alert but then alert is also not working

let aps = remoteNotif["aps"] as? [AnyHashable: Any]
            let string = "\n Custom: \(String(describing: aps))"
            let string1 = "\n Custom: \(String(describing: remoteNotif))"

            DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
                if var topController = application.windows.first?.rootViewController {
                    while let presentedViewController = topController.presentedViewController {
                        topController = presentedViewController
                    }

                    let ac = UIAlertController(title: string1, message: string, preferredStyle: .alert)
                    ac.addAction(UIAlertAction(title: "OK", style: .default))
                    topController.present(ac, animated: true)
                }
            }

How should i solve this problem ?


Solution

  • I have solved it by implementing sceneDelegate willConnectTo method. There is no need to handle it in didFinishLaunchingWithOptions

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    //Remote notification response
       if let response = connectionOptions.notificationResponse{
            print(response.notification.request.content.userInfo)
       }
    
       ....
    } 
    

    This is enough