且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测在未启动应用程序且用户未通过其打开应用程序时是否收到推送通知

更新时间:2023-10-13 15:05:46

在您的AppDelegate中执行此操作(抱歉,无法快速实施):

In your AppDelegate do this (sorry for swift implementation):

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // We see if we have a recent push notification date stored in the user defaults.
    // If there hasn't been a recent one sent this if block will not be entered.
    if let mostRecentPushNotificationDate = NSUserDefaults.standardUserDefaults().objectForKey("mostRecentPushNotification") as? NSDate {

        // We find the difference between when the notification was sent and when the app was opened
        let interval = NSDate().timeIntervalSinceDate(mostRecentPushNotificationDate)

        // Check to see if we opened from the push notification
        if let notification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? [String: AnyObject] {
            print("we opened from the push notifcation and the time difference was \(interval) seconds.")
        }

        // We did not open from a push notification
        else {
            print("we opened from the spring board and the time difference was \(interval) seconds.")
        }

        // We remove the object from the store so if they open the app without a notification being sent we don't check this if block
        NSUserDefaults.standardUserDefaults().removeObjectForKey("mostRecentPushNotification")
    }


    return true
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

    // Set a flag when a push notification was sent
    NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "mostRecentPushNotification")
}