收到通知时,我正在尝试在后台运行此代码:

window?.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
NSNotificationCenter.defaultCenter().postNotificationName("ResetStatusBar", object: nil)

所以我将这段代码放在didReceiveRemoteNotification中,如下所示:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    print("Remote notification received in didReceiveRemoteNotification with fetchCompletionHandler")

    // just pop to rootViewController
    window?.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
    NSNotificationCenter.defaultCenter().postNotificationName("ResetStatusBar", object: nil)
}

当应用程序处于 Activity 状态时,当收到通知时,或者用户单击收到的通知时,将执行此代码,但是,如果我收到通知,请忽略它,然后打开应用程序(我没有杀死,只是按下主页按钮),则更改未在应用程序中生效。

这是我目前正在做的事情:
  • 在推送通知有效载荷
  • 中发送'content-available': 1
  • 在后台模式
  • 的功能下检查remote notifications
    这也是我在AppDelegate文件中注册推送通知的方式:
    let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert,.Badge,.Sound], categories: nil)
    UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
    UIApplication.sharedApplication().registerForRemoteNotifications()
    

    为什么我的代码无法执行?是因为这是UI更改吗?

    附言这是我的推送通知有效负载的样子:
    let payload = {
      default: notificationDisplayText,
      APNS: {
        aps: {
          alert: notificationDisplayText,
          sound: 'default',
          badge: 1,
          'content-available' : 1
        },
        notificationId: notificationId
      }
    }
    

    我将content-available键放在aps对象中是否正确,还是应该将其直接嵌套在APNS对象中?

    最佳答案

    如果您想在应用启动时处理未处理的通知,请使用didFinishLaunchingWithOptions字典中的Swift 3(在Swift 2.3中为.remoteNotification)中的UIApplicationLaunchOptionsRemoteNotificationKey键在launchOptions中进行处理。

    正如the documentation for application(_:didReceiveRemoteNotification:) 所说:

    如果远程通知到达时应用程序未运行,则该方法将启动应用程序并在启动选项字典中提供适当的信息。该应用程序不会调用此方法来处理该远程通知。相反,您对 application(_:willFinishLaunchingWithOptions:) application(_:didFinishLaunchingWithOptions:) 方法的实现需要获取远程通知有效负载数据并进行适当响应。


    无关,请记住,在处理完通知后,必须在didReceiveRemoteNotification中调用completionHandler

    正如the documentation所说(重点在原文中):

    一旦处理完通知,您必须在handler参数中调用该块,否则您的应用将被终止。您的应用最多有30秒的挂钟时间来处理通知并调用指定的完成处理程序块。实际上,您应该在处理完通知后立即调用处理程序块。系统会跟踪您的应用的后台下载所用的时间,用电量和数据费用。处理远程通知时使用大量功能的应用程序可能不会总是很早就被唤醒,以处理将来的通知。

    关于ios - Swift-执行后台任务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41305697/

    10-13 06:16
    查看更多