gpt4 book ai didi

swift2 - UNUserNotificationCenter - 在 for 循环中只安排一个事件,swift 2.3,iOS10,

转载 作者:行者123 更新时间:2023-12-04 18:31:23 24 4
gpt4 key购买 nike

我正在尝试在 for 循环中安排一系列通知。安排后我正在阅读所有待处理的通知(仅用于测试目的)。

调度(从 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,并且预定事件 - 只是我提供给 schedule 方法的列表中的最后一个事件。

在调度期间,我还会打印所有已调度的事件和时间间隔(以确保它在将来),并且我确实获得了我想要调度的所有事件的正确日志,但不知何故,每个下一个事件看起来都覆盖了前一个一。我究竟做错了什么?

最佳答案

问题实际上不是 UNUserNotificationCenter,而是请求的标识符,在我的代码中,它在 for 循环的整个迭代中保持不变。当我向它添加唯一 id 时,它起作用了。

let identifier = NSString.localizedUserNotificationStringForKey("sampleRequest\(event.title)", arguments: nil)

与往常一样,问题比看起来容易得多。

关于swift2 - UNUserNotificationCenter - 在 for 循环中只安排一个事件,swift 2.3,iOS10,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38896385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com