[英]Why I can not get notification from local on iOS with swift 3?
在Swift 3.1的Xcode 8.3上运行
下面是我在AppDelegate.swift中的代码
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in
if granted {
print("User accept notification。")
}
else {
print("User don't like receive any notification!")
}
})
let content = UNMutableNotificationContent()
content.title = "Will it rain?"
content.body = "It never rains in (Southern) California!"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "local_notification", content: content, trigger: trigger)
center.add(request)
return true
}
我在iPhone上构建并运行它,并显示一条消息,询问我是否要接收任何通知,然后单击“接受”。
然后,什么都没有发生。
我希望它会像我的代码中那样显示来自本地的通知,并带有一些文本“ Will it rain”。
您必须使您的AppDelegate才能采用UNUserNotificationCenterDelegate
在applicationDidFinishLaunching
方法中,添加此center.delegate = self
然后执行以下代码:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
}
从Apple Docs:
要响应通知的传递,必须为共享的UNUserNotificationCenter对象实现一个委托。 您的委托对象必须符合UNUserNotificationCenterDelegate协议,通知中心使用该协议将通知信息传递到您的应用程序。 如果您的通知包含自定义操作,则需要委托。
参考: https : //developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SchedulingandHandlingLocalNotifications.html
https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.