【问题标题】:Background fetch not working - Not firing notification后台获取不起作用 - 未触发通知
【发布时间】:2018-07-16 16:15:18
【问题描述】:

我正在尝试在我的应用中实现 Background Fetch API,因为我配置如下。

我已启用从功能获取后台。

在 AppDelegate.swift 中

didFinishLaunchingWithOptions 方法中添加了这个

UIApplication.shared.setMinimumBackgroundFetchInterval(30)

也实现了这个方法来执行任务。

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    debugPrint("New notification fired from AppDelegate...!!")

    let notif = UNMutableNotificationContent()
    notif.title = "New notification from App delegate"
    notif.subtitle = "Cool App!"
    notif.body = "I liked it!"

    UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .badge, .alert], completionHandler: { (isGranted, error) in

        DispatchQueue.main.async {
            let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
            let request = UNNotificationRequest(identifier: "myNotification", content:  notif, trigger: notifTrigger)

            UNUserNotificationCenter.current().add(request) { (error) in
                if error != nil{
                    print(error!)
                } else {
                    // do something
                }
            }
        }
    })

}

配置完所有东西后,本地通知不会触发。为什么会这样?

我错过了什么吗?

我也试过this tutorial

任何帮助将不胜感激!

【问题讨论】:

  • 您应该在应用启动后立即请求通知权限。当您的应用已在后台时,您无法请求权限。
  • 已获得用户通知的权限。
  • 所以从这个函数中取出代码并去掉 dispatchQueue.main

标签: ios swift background-fetch


【解决方案1】:

您没有在performFetchWithCompletionHandler 中调用completionHandler。我可以使用以下代码测试BackgroundFetch

DispatchQueue.main.async {
                let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 6.0, repeats: false)
                let request = UNNotificationRequest(identifier: "myNotification", content:  notif, trigger: notifTrigger)

                UNUserNotificationCenter.current().add(request) { (error) in
                    if error != nil{
                        print(error!)
                        completionHandler(.failed) // Add this line
                    } else {
                        completionHandler(.noData) // Add this line
                    }
                }
            }

您可以通过以下步骤测试后台提取:

  1. 运行您的应用程序。
  2. 转到 Xcode 工具栏。
  3. 选择调试 > 模拟后台提取。

现在您可以测试后台提取了。

【讨论】:

    【解决方案2】:

    关于这个有类似的问题:

    Background Fetch Does Not Appear to Fire

    尝试强制它在模拟器上运行,如果 fetch 事件有效 模拟器,这证明一切都设置正确。有 除了等待,你无能为力。

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 2017-05-31
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多