我一直在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”,但当通知应该被触发时,它从未被触发。我一直无法找到任何解决方法。