我正在尝试通过触发每日通知来测试 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的文档
参数:
Specify false to unschedule the notification after the trigger fires. Specifying true causes the notification to be rescheduled repeatedly.
假设我触发了今天 4/10/2017 下午 6:56 的通知。下午 6:56,我按预期看到了本地通知。
当我尝试通过“设置”->“日期和时间”将日期和时间手动更改为 4/11/2017 下午 6:55 时,一旦下午 6:56 左右,我根本看不到通知。
难道不能这样测试吗?
我没有试过真的等到第二天的指定时间再弹出通知,但我很好奇为什么这种测试方式不起作用?
谢谢。
最佳答案
您在包含日期和月份的日期
调用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)
关于ios - 手动设置时间和日期时,不会触发 iOS 10 中的重复每日本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335557/