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

标签 ios swift swift3 uilocalnotification

我在 ViewController.swift 中创建了一个计划通知,需要将两个操作添加到该通知中。一个说“调用”,另一个说“取消”。如何在 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 设置中心委托(delegate):

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])
}

处理 Action :

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)")
        }
    }
}

请务必在每个使用这些函数的类中导入 UserNotifications

更多信息:User Notifications documentation .

关于ios - 如何在 iOS 10 中替换折旧的 UILocalNotification 并添加 UNNotificationAction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40694750/

相关文章:

ios - 如何撤销 Apple 开发者门户中的分发证书?

ios - 突然 "Could not build Module "来了,它只发生在iOS设备上,在模拟器中它工作正常

ios - Swift 中的链接动画

ios - 从 URL(图片)发出加载 unnotificationAttachment

json - 使用 Swift 3 解析 JSON

swift3 - 每周触发通知 Swift 3

ios - Xcode 7 中 ios 8.0 之前的自动首选最大布局宽度

ios - 无法在 Swift 的 UITextFieldDelegate 类初始值设定项中使用 TextField

swift - Swift 4.0.2 中的 NSObject setValuesForKeys 编码投诉错误

regex - 检查字符串内的值