SWIFT发送本地通知

时间:2018-06-28 10:12:58

标签: swift

我正在尝试按照本教程发送本地通知: 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秒过去了,没有显示任何通知。会以errornil

调用CompletionHandler

1 个答案:

答案 0 :(得分:0)

如果您希望在应用程序处于前台状态时发出通知,则必须在控制器中添加更多代码,

  • viewDidLoad()的末尾添加以下行

    center.delegate = self

    这使ViewController成为通知在命中时可以回调到的委托。

  • 将您的视图控制器确认为委托,(添加UNUserNotificationCenterDelegate

    class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    现在您可以在ViewController中编写回调方法。

  • 编写回调以显示通知,您可以在viewDidLoad()之后添加此方法

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .badge, .sound]) }

    即使应用程序处于前台,这也会使您的通知弹出。

  

注意:强烈建议您在AppDelegate中而非ViewController中注册通知(本地/远程)。