手动设置时间和日期时,iOS 10中的重复每日本地通知不会被触发?

我试图通过尝试触发每日通知来测试iOS 10中的本地通知。

我正在使用以下示例项目: NotificationsUI-Demo

在应用程序中是以下代码之一:

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" if let path = Bundle.main.path(forResource: "logo", ofType: "png") { let url = URL(fileURLWithPath: path) do { let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil) content.attachments = [attachment] } catch { print("The attachment was not loaded.") } } let request = UNNotificationRequest(identifier: "textNotification", 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)") } } let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false) 

我将repeats的值从false更改为true以重复每天,因为根据描述repeats参数的文档:

指定false以在触发器触发后取消计划通知。 指定true会导致重复重新安排通知。

假设我在今天4月10日下午6:56触发通知。 下午6:56,我看到了预期的本地通知。

当我尝试通过设置 – >日期和时间手动将日期和时间更改为下午6:55的4/11/2017,下午6:56到处时,我根本看不到任何通知。

难道不能这样测试吗?

我没有尝试在指定的时间实际等待第二天查看是否会弹出另一个通知,但我很好奇为什么这种测试方式不起作用?

谢谢。

您在具有Date和月份的Date上调用repeats 。 因此,根据法律规定,该日期将永远不会再发生到明年,因此第二天不会发送通知。 通知的触发器必须仅包含使用DateComponents的小时和分钟值,以允许每天重复:

 var date = DateComponents() date.hour = 11 date.minute = 41 let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true) let content = UNNotificationContent() let notification = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger) 

试试这些代码:

 let notificationContent = UNMutableNotificationContent() notificationContent.title = "Title" notificationContent.body = "Body Message" var date = DateComponents() date.hour = 11 date.minute = 30 let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true) let notificationRequest = UNNotificationRequest(identifier: "\(NSDate().timeIntervalSince1970)", content: notificationContent, trigger: notificationTrigger) UNUserNotificationCenter.current().add(notificationRequest) { (error) in if let error = error { let errorString = String(format: NSLocalizedString("Unable to Add Notification Request %@, %@", comment: ""), error as CVarArg, error.localizedDescription) print(errorString) } }