最小化应用程序iOS时如何每隔特定N天推送本地通知?
Posted
技术标签:
【中文标题】最小化应用程序iOS时如何每隔特定N天推送本地通知?【英文标题】:How to push local notification every specific N days when minimize app iOS? 【发布时间】:2019-02-25 10:34:05 【问题描述】:如何在特定 N 天从 DB 获取特定时间(例如:上午 9:00)推送本地通知。我尝试使用计时器来添加通知,但是当我最小化应用程序时,似乎计时器是 suppense。这是我的代码:
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)
【问题讨论】:
【参考方案1】:在 3 天后设置本地推送通知,具体时间为晚上 10:00,当用户打开应用程序或每次我们可以在前台输入应用程序时
applicationDidBecomeActive
委托方法,在这种方法中,如果存在旧的本地推送通知,您需要删除并在 3 天后与特定时间重置。
查看此帖子以设置 N 天的本地推送通知。 Repeating local notifications for specific days of week (Swift 3 IOS 10)
【讨论】:
在那些文章中,看起来我们可以按工作日、日期...等获取日期组件,这对我没有帮助。目前我可以在接下来的 N 天设置通知。但我不知道如何自动重置它。像这样: var dateComponents = DateComponents() dateComponents.day = Date().day + 3 dateComponents.hour = 12 dateComponents.minute = 0 let firstTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)以上是关于最小化应用程序iOS时如何每隔特定N天推送本地通知?的主要内容,如果未能解决你的问题,请参考以下文章
当特定类型的推送通知到达时,如何不允许 iOS 启动应用程序?
在特定时间重复本地通知,并在同一时间后每隔一段时间重复一次本地通知