簡體   English   中英

本地通知swift 3

[英]Local Notifications swift 3

我試圖按下按鈕發送通知。 這是我的viewController中的代碼:

@IBAction func getNotificationButtonPressed(_ sender: Any) {
    let content = UNMutableNotificationContent()
    content.title = "Title"
    content.body = "Body"
    content.categoryIdentifier = "ident"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)

    let request = UNNotificationRequest(identifier: "ident", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()

    center.add(request) { (error : Error?) in
        if let theError = error {
            print(theError.localizedDescription)
        } else {
            print ("success")
        }
    }
}

同樣在AppDelegate中我已經請求使用通知的權限:

let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    application.registerForRemoteNotifications()

PS我已經導入了

import UserNotifications

在AppDelegate和自定義ViewController中。

在該檢查中創建通知時

 if #available(iOS 10.0, *) {
     let content = UNMutableNotificationContent()
     content.title = "Intro to Notifications"
     content.subtitle = "Lets code,Talk is cheap"
     content.body = "Sample code from WWDC"
     content.sound = UNNotificationSound.default()
            // Deliver the notification in five seconds.
     let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)
     let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)

     UNUserNotificationCenter.current().delegate = self
     UNUserNotificationCenter.current().add(request){(error) in

           if (error != nil){

                    print(error?.localizedDescription)
           }
       }
} 

實現此委托方法UNUserNotification用於觸發通知。

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    print("Tapped in notification")
}


//This is key callback to present notification while the app is in foreground
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    print("Notification being triggered")
    //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
    //to distinguish between notifications
    if notification.request.identifier == requestIdentifier{

        completionHandler( [.alert,.sound,.badge])

    }
}

快樂的編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM