【发布时间】: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