如何向UILocalNotification警报添加操作按钮/操作? [英] How can I add action buttons/actions to UILocalNotification alert?
问题描述
我在我的应用程序中安排了本地通知,现在我在向左滑动警报时会收到一般的取消(交叉)按钮。
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我很好奇我是否可以像下面的图片一样添加自定义按钮/操作?
I'm curious if I can add custom buttons/actions to it like on the image below?
推荐答案
我为你准备了一些剪切代码,在 ViewDidLoad
之后10秒显示一个按钮的通知方法确实显示。
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)
}
}
注意:您必须处理AppDelegate方法中的操作:
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.
这段代码是用Swift编写的,但转换为Objective C应该很简单。
This code is written in Swift but convertion to Objective C should be very simple.
这篇关于如何向UILocalNotification警报添加操作按钮/操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!