我正在尝试按照本教程发送本地通知: https://useyourloaf.com/blog/local-notifications-with-ios-10/
我将此代码添加到我的 viewDidLoad()
中:
let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound];
center.requestAuthorization(options: options) {
(granted, error) in
if !granted {
print("Something went wrong")
}
}
let content = UNMutableNotificationContent()
content.title = "Don't forget"
content.body = "Buy some milk"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5,
repeats: false)
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if let error = error {
print("error")
}
})
但是 5 秒过去了,没有显示任何通知。调用 CompletionHandler 时 error
为 nil
最佳答案
如果您希望应用程序位于前台时收到通知,那么您必须在 Controller 中添加更多代码,
在
viewDidLoad() 末尾添加以下行
center.delegate = self
这使得您的 ViewController 成为通知命中时可以回调的委托(delegate)。
向委托(delegate)确认您的 View Controller ,(添加
UNUserNotificationCenterDelegate
)类 ViewController:UIViewController,UNUserNotificationCenterDelegate {
现在您可以在 ViewController 中编写回调方法。
编写回调来呈现您的通知,您可以在
viewDidLoad()
之后添加此方法func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent通知:UNNotification, withCompletionHandler 完成处理程序:@escaping (UNNotificationPresentationOptions) -> Void) { 完成处理程序([.警报,.徽章,.声音]) }
即使应用程序位于前台,这也会弹出通知。
NOTE: It is highly recommended that you register your notifications (Local/Remote) in AppDelegate rather than ViewController.
关于SWIFT 发送本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080239/