我做了一个应用程序,当你点击一个按钮时,它会在一段时间后发送通知。此通知在ViewController中创建。如何让我的应用程序在用户单击通知后执行某些操作?我使用的是swift 3,而不是UILocalNotification。
发布于 2017-02-05 03:36:28
在您的应用委托中,将一个对象配置为用户通知中心的UNUserNotificationCenterDelegate并实现userNotificationCenter(_:didReceive:withCompletionHandler:)。
请注意,如果用户只是关闭通知警报,则不会调用此方法,除非您还使用.customDismissAction选项配置了与此通知对应的类别(UNNotificationCategory)。
发布于 2017-02-05 04:09:35
iOS 10中弃用了UILocalNotification,您应该使用UserNotifications框架。
最重要的是不要忘记import UserNotifications
首先,您应该设置UNUserNotificationCenterDelegate。
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// - Handle notification
}
}而不是设置UNUserNotificationCenter的委托。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (accepted, _) in
if !accepted {
print("Notification access denied.")
}
}
return true
}现在您可以设置通知了。
func setup(at: Date) {
let calendar = Calendar.current
let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current,
month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "Just a reminder"
content.sound = UNNotificationSound.default()
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}并最终处理它!
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "textNotification" {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
guard let rootVc = appDelegate.window?.rootViewController else { return }
let alert = UIAlertController(title: "Notification", message: "It's my notification", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(action)
rootVc.present(alert, animated: true, completion: nil)
}
}
}https://stackoverflow.com/questions/42044543
复制相似问题