如何在应用未运行/ app时处理推送通知

时间:2018-03-14 07:59:02

标签: ios swift push-notification

我正在使用firebase通知。当applicationState是后台时,它工作正常。但是当app没有运行/终止时func getPushNotiData(_ notification:NSNotification)没有被调用

在appDelegate文件中实现NotificationCenter以处理dashView中的通知

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

如果app没有运行/终止在didFinishLaunchingWithOptions委托方法中实现NotificationCenter

 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)
        }
    }

在dashView中处理NotificationCenter

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)
}
}

2 个答案:

答案 0 :(得分:1)

如果应用程序未运行(被杀死状态),则无法执行任何方法或代码,只有当用户单击推送通知时,您才能在@SpringBootApplication class Kotlin2Application //constructor code to print hello world in kotlin fun main(args: Array<String>) { runApplication<Kotlin2Application>(*args) } launchchingOptions中接收它的对象并处理它。 ..

答案 1 :(得分:0)

当您在launchOptions中检查didFinishLaunchingWithOptions时,您的ViewController尚未加载,因此viewDidAppear未被调用且ViewController未在通知中注册,这是可能的。中央。尝试放置一些print语句,并在通知启动应用程序时检查调用的顺序。