首页 > 解决方案 > didReceiveRemoteNotification 当应用程序在后台仅在设备连接到 MacBook 时工作

问题描述

我正在background app refresh使用连接到计算机的设备进行测试。代码正常运行,在didReceiveRemoteNotification调用完成处理程序之前,函数完成:

completionHandler(UIBackgroundFetchResult.newData)

但是,当我断开设备与计算机的连接并尝试相同的操作时,后台应用程序刷新不起作用,并且 didReceiveRemoteNotification 中的代码在应用程序进入前台之前不会运行。

在这两种情况下,无论是否连接到计算机,测试都是在后台模式下使用应用程序完成的。即,未终止且不在前台。

我已确保settings -> general -> background app refresh它在全球范围内为我的应用程序启用。

当完全相同的构建在后台应用程序刷新方面的行为与连接到计算机但未连接的设备不同时,很难进行故障排除。我的代码如下:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    if userInfo["message_id"] as? String != nil {
        MessageHelper().saveServerMessageToLocalDatabase(self.privateContext, serverMessage: userInfo as! [String : AnyObject] completion: { (message: Message?) in
            if message != nil {
                do {
                    try self.privateContext.save()
                    completionHandler(UIBackgroundFetchResult.newData)
                } catch {
                    print("error saving context")
                    completionHandler(UIBackgroundFetchResult.newData)
                }
            } else {
                completionHandler(UIBackgroundFetchResult.newData)
            }
        })
    } else {
        completionHandler(UIBackgroundFetchResult.newData)
    }
}

标签: iosswiftxcodepush-notificationappdelegate

解决方案


如果您使用的是静默通知,

当应用程序处于后台时,静默通知有一定的限制。请参阅下面的 Apple 文档。

在此处输入图像描述

请在此处查看完整文档:以静默方式将更新推送到您的应用程序

当设备连接到您的 Mac 时,所有这些都不适用。该应用程序将在连接时收到所有通知。

另外,请确保回调不会转到以下方法。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

希望能帮助到你。


推荐阅读