我如何才能在特定的N天的特定时间(例如:9:00AM)推送本地通知。我尝试使用计时器添加通知,但是当我最小化应用程序时,似乎计时器是支持的。这是我的代码:
func createTriggerLocalPushNotification(completion: @escaping(Error?) -> ()) {
var date = Date()
date.hour = 12
date.minute = 0
date.second = 0
var timeInterval = 86400 * 3 // Default 3 day
var timeBuffer:TimeInterval = 0
guard let inActivePushString = RealmUserInfo.shared.getValue(with: keyInActiveTimePush),
let inActivePushTime = Int(inActivePushString), inActivePushTime > 0 else {
log.info("Can't trigger inActivePushTime")
return
}
date.add(.day, value: inActivePushTime)
if #available(iOS 10.0, *) {
timeInterval = 86400 * inActivePushTime
timeBuffer = date.timeIntervalSinceNow
let content = UNMutableNotificationContent()
content.body = self.contentMessage
content.sound = UNNotificationSound.default
content.categoryIdentifier = self.inActiveTimePushNotificationCategory
// Buffer trigger when first time
var dateComponents = DateComponents()
dateComponents.day = Date().day + inActivePushTime
dateComponents.hour = 12
dateComponents.minute = 0
let firstTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let requestBuffer = UNNotificationRequest(identifier: self.bufferInActiveTimePushNotification, content: content, trigger: firstTrigger)
UNUserNotificationCenter.current().add(requestBuffer, withCompletionHandler: nil)
// Create content
Timer.scheduledTimer(withTimeInterval: timeBuffer, repeats: false) { (timer) in
// Create trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timeInterval), repeats: true)
let request = UNNotificationRequest(identifier: self.inActiveTimePushNotification, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
completion(nil)
} else {
// Fallback on earlier versions
let content = UILocalNotification()
content.alertBody = contentMessage
content.soundName = UILocalNotificationDefaultSoundName
content.category = inActiveTimePushNotification
content.fireDate = date
content.repeatInterval = .day
UIApplication.shared.scheduleLocalNotification(content)
completion(nil)
}
}
答案 0 :(得分:0)
在3天后的特定时间(例如晚上10:00)设置本地推送通知,当用户打开应用程序时,或者每次我们可以获取前台应用程序时,
applicationDidBecomeActive
委托方法,在这种方法中,您需要删除旧的本地推送通知(如果存在),并在3天后的特定时间重置。
请参阅此帖子以设置N天的本地推送通知。 Repeating local notifications for specific days of week (Swift 3 IOS 10)