【发布时间】:2017-01-26 23:36:53
【问题描述】:
我一直致力于在 iOS 10 中为我的应用程序设置本地通知,但在模拟器中进行测试时,我发现通知会成功安排,但在安排的时间到来时不会真正出现。这是我一直在使用的代码:
let UNcenter = UNUserNotificationCenter.current()
UNcenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
// Enable or disable features based on authorization
if granted == true {
self.testNotification()
}
}
然后它运行这段代码(假设日期/时间在未来):
func testNotification () {
let date = NSDateComponents()
date.hour = 16
date.minute = 06
date.second = 00
date.day = 26
date.month = 1
date.year = 2017
let trigger = UNCalendarNotificationTrigger(dateMatching: date as DateComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = "TestTitle"
content.body = "TestBody"
content.subtitle = "TestSubtitle"
let request = UNNotificationRequest(identifier: "TestID", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("error: \(error)")
} else {
print("Scheduled Notification")
}
}
}
从这段代码中,它总是会打印“Scheduled Notification”,但是当通知应该被触发时,它永远不会触发。我一直找不到任何解决方法。
【问题讨论】:
-
当通知应该被触发时,您的应用程序是否在前台?
-
不,我确保在通知触发之前退出应用程序。当应用程序处于后台、完全关闭以及显示锁定屏幕时,我已经尝试过。没有工作。
-
您是手动更改设备的时间来测试它吗?
-
@bhakti123 在测试之前,我会检查时间并将 date.hour 和 date.minute 更改为提前几分钟。然后我进行测试,它会收到预定的通知,然后我关闭了应用程序。我根本不更改设备的时间,只是安排通知的时间。
-
尝试将标识符“testId”更改为其他内容,具有相同标识符的通知将被拒绝。所以也许它第一次安排了通知,这就是它拒绝其他通知的原因。
标签: notifications swift3 ios10 ios10.2