【问题标题】:Detect if app is not opened via push notification in iOS?检测是否未通过 iOS 中的推送通知打开应用程序?
【发布时间】:2017-01-27 10:26:29
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以查看“applicationdidfinishlauching”方法。当用户单击应用程序图标时应用程序启动时调用它。
  • 并且通过push打开它时没有调用它?谢谢!
  • 如果应用程序已经在后台运行,则否。
  • 取一个布尔变量并将其设置为 yes 如果 didRecieveRemoteNotification 被调用并将其存储在 NSUserdefaults 中
  • appDidFinishLaunching 方法应该在其内部的选项字典中包含通知的数据。如果应用程序正在启动(如它被终止然后启动)并带有通知,那么您将能够在那里检查它

标签: ios swift push-notification


【解决方案1】:

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

然后在你的 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
         }
     }
}

}

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

override func viewDidLoad() {
    super.viewDidLoad()
    
    if pushNotifcationLaunch = false {
         //Code for did launched via app click.
    }
}

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 2013-04-29
    • 2016-06-22
    • 2015-11-17
    • 1970-01-01
    • 2014-06-06
    • 2016-11-07
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多