AbhiRaz
AbhiRaz

Reputation: 132

How to handle push notification when app is not running/app is terminated

I am using firebase notification. When applicationState is background it's working fine. But when app is not running / terminated func getPushNotiData(_ notification: NSNotification) is not being call

Implementing NotificationCenter in appDelegate file to handle notification in dashView

func application(_ application: UIApplication, didReceiveRemoteNotification 
userInfo: [AnyHashable : Any]) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: 
"getPushNotificationData"), object: nil, userInfo: userInfo)
}

And if app is not running / terminated Implementing NotificationCenter in didFinishLaunchingWithOptions delegate method

 if (launchOptions != nil)
    {
        let userInfo = launchOptions![.remoteNotification] as? [AnyHashable: Any]
        if userInfo != nil {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "getPushNotificationData"), object: nil, userInfo: userInfo)
        }
    }

Handling NotificationCenter in dashView

override func viewDidAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(self.getPushNotiData(_:)), name: NSNotification.Name(rawValue: "getPushNotificationData"), object: nil)
}

@objc func getPushNotiData(_ notification: NSNotification){
    if let url = notification.userInfo!["url"] as? String {
        let destination = storyboard?.instantiateViewController(withIdentifier: "NotificationDlsViewController") as! NotificationDlsViewController
        destination.notiUrl = url
        self.navigationController?.pushViewController(destination, animated: true)
}
}

Upvotes: 1

Views: 3097

Answers (2)

LorenzOliveto
LorenzOliveto

Reputation: 7936

It's probabile that when you check launchOptions in your didFinishLaunchingWithOptions your ViewController is not loaded yet so viewDidAppear has not been called and the ViewController is not registered in the Notification Center. Try to put some print statement and check the order of the calls when the app is launched from the notification.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

If the app is not running (killed state) , you can't execute any methods or code , only if the user clicks the push notification you can receive object of it in didFinishLaunchingWithOptions launchingOptions and handle it ....

Upvotes: 2

Related Questions