Как я могу отправить локальное уведомление в определенное время (например, 9:00 утра) в определенный N день получить из БД.Я попытался таймер, чтобы добавить уведомление, но кажется, что таймер является принудительным, когда я свернуть приложение.Вот мой код:
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)
}
}