使用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上构建并运行它,并会显示一条消息,询问我是否希望收到任何通知,然后点击接受。
然后,没有任何事情发生。
我希望它会显示来自当地的通知以及一些文字"会下雨"就像在我的代码中一样。
答案 0 :(得分:0)
您必须让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/reference/usernotifications/unusernotificationcenterdelegate