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

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

本文介绍了检测在未启动应用程序且用户未通过其打开应用程序时是否收到推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能检测应用程序处于脱机状态时是否收到了推送通知(不在后台或前台?如果用户直接从弹簧板上而不是从推送通知警报中打开应用程序,则为这种情况.

Is it possible to detect if a push notification was received while the app was offline (not in background or foreground ? given the case that the user open the app directly from the spring board and not from the push notification alert.

推荐答案

在您的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")
}

这篇关于检测在未启动应用程序且用户未通过其打开应用程序时是否收到推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 19:26