Swift 4 получает push-уведомление с таймером - PullRequest
0 голосов
/ 31 августа 2018

У меня есть userNotificationCenter willPresent func (). Что я хочу сделать, это ... получить уведомление один раз, а затем получать одно уведомление каждые 5 минут, если они существуют. Как я могу это сделать?

userNotificationCenter:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    //checkUser - current account ID
    //userID - from user
    var timer = Timer()

        let userID : String = (EVTUser.user?.id)!
        if let checkUser = notification.request.content.userInfo["user_id"]{

            if userID != checkUser as! String{
                guard let _ = UIViewController.visibleChatViewController() else {
                    completionHandler([.badge, .alert, .sound])
                    return
                }
                EVTChatLogController.receiveMessage(notification: notification.request.content)

                //Push display
                if isTransitionChat {
                    isTransitionChat = false
                    completionHandler([.badge, .alert, .sound])
                    AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
                }
            }
            else{
                return
            }
        }
        else{
            guard let _ = UIViewController.visibleChatViewController() else {
                completionHandler([.badge, .alert, .sound])
                return
            }

            EVTChatLogController.receiveMessage(notification: notification.request.content)

            if isTransitionChat {

                isTransitionChat = false
                completionHandler([.badge, .alert, .sound])

                AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
            }

}

ОБНОВЛЕНИЕ: Я пытался использовать этот код, но все равно безуспешно ...

let uuidString = UUID().uuidString
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (5*60), repeats: true)
    let request = UNNotificationRequest(identifier: uuidString, content: notification.request.content, trigger: trigger)

    // Schedule the request with the system.
    let notificationCenter = UNUserNotificationCenter.current()
    notificationCenter.add(request) { (error) in
        if error != nil {

        }
    }

1 Ответ

0 голосов
/ 03 сентября 2018

Попробуйте проверить приведенный ниже код. В соответствии с моим пониманием, я думаю, что вам просто нужно отправить уведомление с тем же содержанием через определенный промежуток времени

import UserNotifications

struct NotificationHandlerStruct {
    static var notifyTimer : Timer?
}

class LocalNotificationHandler: NSObject, UNUserNotificationCenterDelegate
{
    static var shared = LocalNotificationHandler()

    //MARK: Schedule Notification
    func scheduleNotification(Title title: String, Subtitle subtitle: String, BodyMessage body: String) {
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
        let content = UNMutableNotificationContent()
        //adding title, subtitle, body and badge
        content.title = title
        content.subtitle = subtitle
        content.sound = UNNotificationSound.default()
        content.body = body
        content.badge = 0
        content.userInfo = ["type":"calling"]

        //getting the notification trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
        //getting the notification request
        let request = UNNotificationRequest(identifier: "Call", content: content, trigger: trigger)
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

        if NotificationHandlerStruct.notifyTimer == nil {
            NotificationHandlerStruct.notifyTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
                self.sendNotification(NotificationContent: content)
            })
        }
        else{
            NotificationHandlerStruct.notifyTimer?.invalidate()
            NotificationHandlerStruct.notifyTimer = nil
        }

    }

    //MARK: Repeat Notification
    func sendNotification(NotificationContent content: UNMutableNotificationContent) {
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
        //getting the notification trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
        //getting the notification request
        let request = UNNotificationRequest(identifier: "Call", content: content, trigger: trigger)
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    //MARK: Stop Timer
    func stopTimer() {
        if NotificationHandlerStruct.notifyTimer != nil {
            NotificationHandlerStruct.notifyTimer?.invalidate()
            NotificationHandlerStruct.notifyTimer = nil
        }
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
}

Пока пользователь открывает это конкретное уведомление, просто делает недействительным таймер

или

Скажите, пожалуйста, что именно вы ищете

...