场景是:我需要为一组对象触发本地通知,每个对象在固定的时间间隔(以秒为单位)后,如果我提供固定的秒数,这里的代码仅适用于 1 个间隔
func DeliverMyMessage(_ dict: EnFact, _ index: Int){
let content = UNMutableNotificationContent();
content.body = dict.Content!;
content.categoryIdentifier = "learn";
content.userInfo = ["dictid": "Random Fact -\(dict.ID!)- \(dict.Reference!)" ];
content.sound = UNNotificationSound.default();
content.badge = 1;
print(secArray[index]);
var ui = TimeInterval.init(secArray[index]);
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
cnter.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print(error);
}
print("delivered");
})
}
注意: UNTimeIntervalNotificationTrigger(timeInterval: 5 如果我提供了一个固定间隔,假设为 5 - 我从数组中触发的所有通知,在 5 秒后触发,
然后,如果我尝试在循环中以秒为单位给出计算出的差异,则通知似乎不会触发
func DeliverMyMessage(_ dict: EnFact, _ index: Int){
let content = UNMutableNotificationContent();
content.body = dict.Content!;
content.categoryIdentifier = "learn";
content.userInfo = ["dictid": "Random Fact -\(dict.ID!)- \(dict.Reference!)" ];
content.sound = UNNotificationSound.default();
content.badge = 1;
print(secArray[index]);
var ui = TimeInterval.init(secArray[index]);
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5 + ui , repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
cnter.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
print(error);
}
print("delivered");
if(index < ( self.dictArray.count - 1) ){
self.DeliverMyMessage(self.dictArray[index + 1], index + 1);
}else{
print("all delivered");
}
})
}
它说明所有交付但它不是,我使用的是 iOS 11.3 XCode 9.3 swift 4,我坚持使用它,因为这是我需要在项目中做的最后一部分 - 非常感谢任何帮助