在 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)

無論何時觸發此部分程式碼,如果你已經允許通知許可權,你將收到通知。

要正確測試,請確保你的應用程式處於後臺模式。