如何在特定的N天从DB获取特定时间(例如:上午9:00)的本地通知。我尝试使用计时器来添加通知,但是当我最小化应用程序时,看起来似乎是计时器。这是我的代码:
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)
}
}
在3天之后设置本地推送通知,具体时间如下午10:00,当用户打开应用程序时或者每次我们可以获得applicationDidBecomeActive
委托方法时只需在前台输入应用程序,在此方法中,如果存在,则需要删除旧的本地推送通知在特定时间后3天后重置。
请参阅此帖子以设置N天的本地推送通知。 Repeating local notifications for specific days of week (Swift 3 IOS 10)