检测iOS中的推送通知是否未打开应用程序?

时间:2017-01-27 10:26:29

标签: ios swift push-notification

我从另一个堆栈溢出帖子中获取此解决方案,以检测是否通过推送通知打开了应用程序:

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    print("Push notification received: \(data)")
    if #available(iOS 9, *) {
    if let type = data["type"] as? String, type == "status" {
        // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
        if application.applicationState != UIApplicationState.background && NSDate().timeIntervalSince(wakeTime as Date) < 0.1 {
            // User Tap on notification Started the App
            sendPushStatistic()
        }
        else {
            // DO stuff here if you ONLY want it to happen when the push arrives
        }
    }
    else {
    }
    }
}

现在我想知道如何在不点击推送通知但是通过应用程序图标或正在运行的应用程序视图中查看应用程序是否已打开(冷启动和后台)?

1 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是在上面的函数中添加一个布尔值,指出它是否是通过推送通知打开的。

然后在viewdidLoad中,您可以检查此布尔值。

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
print("Push notification received: \(data)")
if #available(iOS 9, *) {
if let type = data["type"] as? String, type == "status" {
    // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
    if application.applicationState != UIApplicationState.background && NSDate().timeIntervalSince(wakeTime as Date) < 0.1 {
        // User Tap on notification Started the App
        sendPushStatistic()
    }
    else {
        pushNotificationLaunch = true

    }
}
else {
}
}

}

然后在viewDidLoad函数中,您可以创建一个if语句来查看创建的变量是否为真。

override func viewDidLoad() {
    super.viewDidLoad()

    if pushNotifcationLaunch = false {
    //Code for did launched via app click.
}