簡體   English   中英

最小化App iOS時,如何每隔N天推送一次本地通知?

[英]How to push local notification every specific N days when minimize app iOS?

我如何在N天的特定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)
    }
}

在3天后的特定時間(如晚上10:00)設置本地推送通知,當用戶打開應用程序或每次我們可以獲取applicationDidBecomeActive委托方法時只需在前台輸入應用程序時,在這種方法中,您需要刪除舊的本地推送通知(如果存在)在特定時間3天后重設。

請參閱此帖子以設置N天的本地推送通知。 在一周的特定日期重復本地通知(Swift 3 IOS 10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM