在 Swift 3.0 中注册和安排本地通知(iOS 10)

注册

AppDelegate 中

import UserNotifications

didFinishLaunchingWithOptions 方法中,

UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in

// Here you can check Request is Granted or not.

}

创建和安排通知。

    let content = UNMutableNotificationContent()
    content.title = "10 Second Notification Demo"
    content.subtitle = "From Wolverine"
    content.body = "Notification after 10 seconds - Your pizza is Ready!!"
    content.categoryIdentifier = "myNotificationCategory"

    let trigger = UNTimeIntervalNotificationTrigger(
        timeInterval: 10.0,
        repeats: false)
    
    let request = UNNotificationRequest(
        identifier: "10.second.message",
        content: content,
        trigger: trigger
    )
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

无论何时触发此部分代码,如果你已经允许通知权限,你将收到通知。

要正确测试,请确保你的应用程序处于后台模式。