“稍后提醒我”本地通知的function
我想通过添加“稍后提醒我”操作来扩展我的本地通知function。 换句话说,如果用户点击“稍后提醒我”按钮,我想在一段时间后重新发出通知。
即使所有内容都应该在我的应用程序中正确连接(检查通知是否已启用,设置通知类别和委托,处理提醒我以后的function),在点击提醒稍后按钮后安排的通知根本不显示。
设置一切(检查权限,设置类别)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {(accepted, error) in if !accepted { print("Notification access denied.") } } let action = UNNotificationAction(identifier: "remindLater", title: "Remind me later", options: []) let category = UNNotificationCategory(identifier: "myCategory", actions: [action], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([category]) return true }
处理点击“稍后提醒我”
@available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if response.actionIdentifier == "remindLater" { let newDate = Date(timeInterval: 10, since: Date()) scheduleNotification(at: newDate, withCompletionHandler: { completionHandler() }) } }
设置本地通知的实际代码:
func scheduleNotification(at date: Date) { let calendar = Calendar(identifier: .gregorian) 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 = "Tutorial Reminder" content.body = "Just a reminder to read your tutorial over at appcoda.com!" content.sound = UNNotificationSound.default() content.categoryIdentifier = "myCategory" let request = UNNotificationRequest(identifier: date.description, content: content, trigger: trigger) UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().removeAllPendingNotificationRequests() UNUserNotificationCenter.current().add(request) {(error) in if let error = error { print("Uh oh! We had an error: \(error)") } } }
我究竟做错了什么? 我正在使用AppCoda iOS 10用户通知指南。 这是示例代码 。
问题是您需要为您正在安排的每个通知使用唯一标识符。 您可以使用触发日期说明。 不要忘记您需要关闭您的应用才能收到通知。