每次应用程序执行后台获取或与蓝牙设备同步时,我都需要创建一个本地 UserNotification。问题是 iOS 10 之前的旧本地通知有效,现在新的 UserNotifications 不起作用/触发,什么也没有发生。有没有关于这个问题的解决方案?
目前我的测试代码如下:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
print("NOT authorized")
}
}
let content = UNMutableNotificationContent()
content.title = "MyApp"
content.body = "oi"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
let notification = UNNotificationRequest(identifier: "timer", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(notification) { (error) in
if error != nil {
print("DID NOT CREATE NOTIFICATION")
}else{
print("CREATED NOTIFICATION")
}
}
扩展 AppDelegate:UNUserNotificationCenterDelegate {
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: > @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, > >didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
} }
好的,我找到问题了,我缺少请求授权码。
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句