[英]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.