簡體   English   中英

如何在iOS 10中替換已貶值的UILocalNotification並添加UNNotificationAction

[英]How to replace depreciated UILocalNotification and add UNNotificationAction in iOS 10

我已經在ViewController.swift中創建了計划通知,並且需要將兩個操作添加到此通知中。 一個說“ Call”,另一個說“ Cancel”。 如何在ViewController.swift中添加這些操作? 這是代碼的一部分,具有在ViewController.swift中觸發通知的功能:

func notificationFires(){

    let notification = UILocalNotification()
    // 2
    notification.soundName = UILocalNotificationDefaultSoundName
    notification.fireDate = datePicker.date

    // 3
    if textField.text == "" {

        notification.alertBody = "You have a call right now!"

    }
    else{

        notification.alertBody = self.textField.text

    }
    // 4
    notification.timeZone = NSTimeZone.default
    // 5
    // 6
    notification.applicationIconBadgeNumber = 1
    // 7
    UIApplication.shared.scheduleLocalNotification(notification)



    func application(application: UIApplication,  didReceiveRemoteNotification userInfo: [NSObject : AnyObject],  fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
        print("Recived: notification")



        if cancelled == true{
            print("cancelled happened")

        }
        func cancelNotify(){
            cancelled = true
            UIApplication.shared.cancelAllLocalNotifications()
        }
        completionHandler(.newData)

    }

}

我還沒有在iOS 10中使用過通知,所以我繼續將其視為對自己的學習體驗,現在我可以將其傳遞給您。

UILocalNotification在iOS 10中已棄用,並由UserNotifications框架取代。

在您的AppDelegate獲得用戶授權以顯示通知並使用UNUserNotificationCenterDelegate設置中心委托:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let center = UNUserNotificationCenter.current()
    center.delegate = self
    let options: UNAuthorizationOptions = [.alert, .sound];
    center.requestAuthorization(options: options) {
        (granted, error) in
        if !granted {
            print("Something went wrong")
        }
    }

    return true
}

向用戶顯示通知:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // Play sound and show alert to the user
    completionHandler([.alert,.sound])
}

處理動作:

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

    // Determine the user action
    switch response.actionIdentifier {
    case UNNotificationDismissActionIdentifier:
        print("Dismiss Action")
    case UNNotificationDefaultActionIdentifier:
        print("Default")
    case "foo":
        print("foo")
    case "bar":
        print("bar")
    default:
        print("Unknown action")
    }
    completionHandler()
}

無論您想為應用中的所有通知設置所有操作和類別,都可以執行此操作。 因為它們被分配給中心,而不是通知本身:

func setupActions() {

    //create first action
    let foo = UNNotificationAction(
        identifier: "foo",
        title: "foo"
    )

    //create second action
    let bar = UNNotificationAction(
        identifier: "bar",
        title: "bar",
        options: [.destructive]
    )

    //put the two actions into a category and give it an identifier
    let cat = UNNotificationCategory(
        identifier: "cat",
        actions: [foo, bar],
        intentIdentifiers: []
    )

    //add the category to the notification center
    UNUserNotificationCenter.current().setNotificationCategories([cat])
}

最后創建實際的通知:

func setupNotification() {

    let content = UNMutableNotificationContent()

    content.title = "Hello!"
    content.body = "A message"
    content.sound = UNNotificationSound.default()

    //make sure to assign the correct category identifier
    content.categoryIdentifier = "cat"

    // Deliver the notification in five seconds.
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "hello", content: content, trigger: trigger)
    let center = UNUserNotificationCenter.current()

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

確保使用這些功能在每個類中import UserNotifications

更多信息: 用戶通知文檔

暫無
暫無

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

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