我正試圖在for循環中安排一系列通知。安排後,我正在閱讀所有待處理的通知(僅用於測試目的)。UNUserNotificationCenter - 僅在for循環中安排一個事件,swift 2.3,iOS10,
調度(從for循環調用):
func scheduleNotification (event : Meeting, todaysBadgeCounter: Int) {
if #available(iOS 10.0, *) {
let minutesBefore = CallIn.Settings.notifyNumberOfMinutesBeforeEvent
let notifyBefore = UNNotificationAction(identifier: NotificationActions.NotifyBefore.rawValue, title: "Notification", options: [])
let category = UNNotificationCategory(identifier: "CALLINNOTIFICATION", actions: [notifyBefore], intentIdentifiers: [], options: [])
UNUserNotificationCenter.currentNotificationCenter().setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationStringForKey(event.title, arguments: nil)
if(minutesBefore <= 1){
content.body = NSString.localizedUserNotificationStringForKey("Your \(event.title) is about to start", arguments: nil)
}else{
content.body = NSString.localizedUserNotificationStringForKey("You have \(event.title) in \(Int(minutesBefore)) minutes", arguments: nil)
}
content.sound = UNNotificationSound.defaultSound()
//interval in seconds from current point in time to notification
let interval : NSTimeInterval = NSTimeInterval(secondsFromNowTo(event.startTime.dateByAddingTimeInterval(-minutesBefore * 60)))
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: interval, repeats: false)
let request = UNNotificationRequest.init(identifier: "sampleRequest", content: content, trigger: trigger)
//only schedule in the future
if(interval > 0){
UNUserNotificationCenter.currentNotificationCenter().addNotificationRequest(request, withCompletionHandler: { (error) in
// handle the error if needed
log.error(error?.localizedDescription)
print("SCHEDULING >=iOS10:", event.title, ", interval:", interval)
})
}
}
讀:
func printScheduledNotifications() {
if #available(iOS 10.0, *) {
print("printing scheduled notifications >=iOS10")
UNUserNotificationCenter.currentNotificationCenter().getPendingNotificationRequestsWithCompletionHandler({ (notifications) in
print("count", notifications.count)
for notification in notifications{
print(notification.description)
}
})
}
「通知」,在後者的方法是UNNotificationRequest陣列,但這種陣列返回的計數總是1,而排定的事件 - 只是我提供給排程方法的列表中的最後一個事件。
在排期期間,我還打印了所有預定的事件和時間間隔(以確保它是在將來),並且我確實記錄了所有要安排的事件的日誌,但不知何故,事件會覆蓋前一個事件。我究竟做錯了什麼?
現在,當我在任何地方設置斷點時,我發現UNUserNotificationsCenter的實例在任何地方都不同。這可能是問題。我需要使它成爲一個單一的實例,這很奇怪,爲什麼它已經不是這樣了.. –
我創建了一個單例,現在它是相同的實例,但仍然沒有幫助 –