如何替换折旧的UILocalNotification并在iOS 10中添加UNNotificationAction

时间:2016-11-19 15:43:31

标签: ios swift swift3 uilocalnotification

我在ViewController.swift中创建了一个预定通知,需要将两个操作添加到此通知中。一个说" Call",另一个说"取消"。如何在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)

    }

}

1 个答案:

答案 0 :(得分:3)

我还没有在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

更多信息:User Notifications documentation