How can I add action buttons/actions to UILocalNotification alert?

痞子三分冷 提交于 2019-11-27 17:01:15

问题


I have a local notification scheduled in my app, and right now I get a generic cancel (cross) button as I swipe the alert to the left.

I'm curious if I can add custom buttons/actions to it like on the image below?


回答1:


I prepared for you some snipped code which shows notification with one button 10 second after ViewDidLoad method did shown.

  import UIKit

    class TestViewController: UIViewController {

        let category = UIMutableUserNotificationCategory()

        override func viewDidLoad() {
            super.viewDidLoad()

            let restartAction = UIMutableUserNotificationAction()
            restartAction.identifier = "xx"
            restartAction.destructive = false
            restartAction.title = "Restart"
            restartAction.activationMode = .Background
            restartAction.authenticationRequired = false

            let categoryIdentifier = "category.identifier"
            category.identifier = categoryIdentifier
            category.setActions([restartAction], forContext: .Minimal)
            category.setActions([restartAction], forContext: .Default)

            let categories = Set(arrayLiteral: category)
            let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: categories)
            UIApplication.sharedApplication().registerUserNotificationSettings(settings)


            let localNotif = UILocalNotification()
            localNotif.alertBody = "testBody"
            localNotif.category = categoryIdentifier

            // Notification will be shown after 10 second (IMPORTANT: if you want to see notification you have to close or put app into background)
            localNotif.fireDate = NSDate().dateByAddingTimeInterval(10)
            UIApplication.sharedApplication().scheduleLocalNotification(localNotif)
        }

    }

Note: you have to handle action in AppDelegate method:

func application(application: UIApplication, handleActionWithIdentifier identifier: String?,
                forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {

  completionHandler()
}

Of course my code is not as clean as it should be, but you have to know that I wrote it only for presentation purposes.

This code is written in Swift but convertion to Objective C should be very simple.



来源:https://stackoverflow.com/questions/34144510/how-can-i-add-action-buttons-actions-to-uilocalnotification-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!