当应用程序处于前台时,如何在点击推送通知时执行操作,而不是自己执行操作?

时间:2018-09-26 06:02:34

标签: ios swift xcode push-notification

当前我正在使用下面提到的代码

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
    completionHandler(.alert)
    let aps = notification.request.content.userInfo[AnyHashable("aps")] as! NSDictionary
    let alert = aps["alert"] as! String
    if alert == "Welcome to XYZ. To place order please click here"{
        let stryBrd = UIStoryboard(name: "Main", bundle: nil)
        let vc = stryBrd.instantiateViewController(withIdentifier: "viewController")  as! viewController
        self.window?.rootViewController = vc
    }else{
        print("false")
    }
}

但是在此代码中,应用程序会自动运行到所需的视图控制器,而我希望仅当用户点击通知时它才会发生。

当应用程序在后台运行时,它可以正常工作。只有当我们点击通知时,这种情况才会发生

它应该与WhatsApp相同。当您与ABC先生聊天且PQR小姐向您发送文本时,它将显示推送信息,但除非您点击该按钮以打开PQR小姐聊天,否则它不会做任何事情。

1 个答案:

答案 0 :(得分:0)

使用UIAlertController显示推送通知,然后点击按钮以编写代码以执行操作

    let stryBrd = UIStoryboard(name: "Main", bundle: nil)
    let vc = stryBrd.instantiateViewController(withIdentifier: "viewController")  as! viewController
    self.window?.rootViewController = vc

更多说明:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
    completionHandler(.alert)
    let aps = notification.request.content.userInfo[AnyHashable("aps")] as! NSDictionary
    let alert = aps["alert"] as! String
    if alert == "Welcome to XYZ. To place order please click here"{

        //show alert to the user after getting push notification

        let myalert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        myalert.addAction(UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in

            //perform action of push notification

            let stryBrd = UIStoryboard(name: "Main", bundle: nil)
            let vc = stryBrd.instantiateViewController(withIdentifier: "viewController")  as! viewController
            self.window?.rootViewController = vc
        })
        myalert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in
            //handle cancel event
        })

        currentViewController.present(myalert, animated: true)
    }else{
        print("false")
    }
}