为什么我无法通过swift 3从iOS上获取本地通知?
问题描述:
与SWIFT 3.1为什么我无法通过swift 3从iOS上获取本地通知?
下面运行上的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上运行,并会显示一条消息,问我是否愿意接受任何通知,我点击接受。
然后,什么也没有发生。
我希望它会显示来自本地的通知,并在文本中显示“会下雨”,就像我的代码一样。
答
你必须让你的AppDelegate采用UNUserNotificationCenterDelegate
在applicationDidFinishLaunching
方法,添加此center.delegate = self
然后执行以下代码:
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert])
}
}
从苹果文档:
为了响应通知的传递,您必须进入为共享UNUserNotificationCenter对象提供 委托。您的代理 对象必须符合UNUserNotificationCenterDelegate协议, ,通知中心使用该协议将通知信息 传送到您的应用程序。如果您的通知包含 自定义操作,则需要委托人。
https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate
你有没有实现的'UNUserNotificationCenterDelegate'的方法呢? –
确保关闭你的应用程序,否则你将不会收到任何通知,5秒间隔太接近 –
另一个想法是你需要确保你指定一个不同的标识符。你应该使用触发日期描述来确保你为每个请求分配一个唯一的标识符 –