我制作了一个应用程序,在您单击按钮一段时间后发送通知。此通知是在ViewController中创建的。在用户点击通知后,如何让我的应用程序执行某些操作?我正在使用swift 3而不使用UILocalNotification。
答案 0 :(得分:2)
在您的app delegate中,将对象配置为用户通知中心的UNUserNotificationCenterDelegate并实施userNotificationCenter(_:didReceive:withCompletionHandler:)
。
请注意,如果用户仅仅取消通知提醒,则此方法将不称为,除非您还配置了与此通知对应的类别(UNNotificationCategory), .customDismissAction
选项。
答案 1 :(得分:2)
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)
}
}
}