【问题标题】:Push notification when app is terminated应用程序终止时推送通知
【发布时间】:2016-03-25 19:20:09
【问题描述】:

如果应用程序在后台和/或如果应用程序在前台,我的应用程序可以很好地处理推送通知。

我遇到的问题是应用程序是否终止(我通过双击主页按钮,找到应用程序并向上滑动来强制终止)。

我正在使用 ios 9 和 swift 2。

在应用委托中,didFinishLaunchingWithOptions,我这样做:

let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)

application.registerUserNotificationSettings(settings)

application.registerForRemoteNotifications()

然后:

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {        
        application.registerForRemoteNotifications()
}

之后是 didRegisterForRemoteNotificationsWithDeviceToken 和 didFailToRegisterForRemoteNotificationsWithError。

那么,我用的是比较新的方法:

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

根据文档和这个link,与旧版本的didReceiveRemoteNotification相反,如果应用程序被终止,则调用此方法(与调用will/did finishLaunchingWithOptions相反)。

但是,如果有推送(已收到 - 我可以在屏幕上看到)并且我在应用程序终止后启动应用程序,则似乎不会调用此方法作为处理推送的代码 (只需发布一个通知,以便相应的 ViewController 接收它)不会被调用。

我错过了什么?我需要在 didFinishLaunchingWithOptions 中进行额外检查吗?其他地方?

【问题讨论】:

    标签: ios push-notification apple-push-notifications swift2


    【解决方案1】:

    设法解决了当应用程序在 ios 9.1 中终止时拦截远程推送的问题,但它在 9.2 上失败(随机失败?):

    远程注册:

    if #available(iOS 9, *) {
    
                let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
    
                //            UIApplication.sharedApplication().registerUserNotificationSettings(settings)
                //
                //            UIApplication.sharedApplication().registerForRemoteNotifications()
    
                application.registerUserNotificationSettings(settings)
    
                application.registerForRemoteNotifications()
    
    } else if #available(iOS 8.0, *){
      register for 8...
    } else { //ios 7
      register for 7...
    }
    
    
    if let _ = launchOptions {
    
           if let _ = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
    
                    handleRemotePush()
    
                } else if let _ = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
    
                    handleLocalNots()
    
                } else {
    
                    handleElse()
    
            }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多