Обратный вызов после получения уведомления в фоновом режиме и на переднем плане - PullRequest
0 голосов
/ 03 сентября 2018

Я просматривал различную документацию Apple API, но я не нашел четкого ответа относительно того, какие методы использовать, чтобы обнаружить, было ли доставлено уведомление из моего приложения в фоновом режиме и на переднем плане. В частности, я хотел бы запланировать новое уведомление, как только будет получено другое. Использование Swift 4, но приветствуются объективные решения

Ответы [ 2 ]

0 голосов
/ 20 октября 2018

Спасибо за ваши ответы. Размещать это, чтобы помочь другим.

Чтобы добиться фоновой обработки уведомлений, вы должны использовать расширенную концепцию программирования глобальных переменных (введена в Swift 4)

//in ViewController.swift
var showNotificationsInBackground : Bool = true

Это все, что вам нужно сделать, чтобы заставить это работать! Спасибо за ваше время и 15 баллов! :)

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

Обеспечение доступности содержимого: 1 доступно в полезной нагрузке для фонового уведомления, а вот

// Push notification received
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Error = ", error.localizedDescription)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    let state = application.applicationState
    DispatchQueue.main.async { // active
        if state == .active {
            PushManager.object().handlePushNotification(userInfo, isCameFromForeground: true)
        } else if state == .background {
            PushManager.object().handlePushNotification(userInfo)
        } else {
            PushManager.object().handlePushNotification(userInfo)
        }
    }
    completionHandler(.newData)
}
// Notification handling for iOS 10
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let data = notification.request.content.userInfo
    let state = UIApplication.shared.applicationState
    DispatchQueue.main.async { // active
        if state == .active {
            PushManager.object().handlePushNotification(data, isCameFromForeground: true)
        } else if state == .background {
            PushManager.object().handlePushNotification(data)
        } else {
            PushManager.object().handlePushNotification(data)
        }
    }
    completionHandler([.alert, .badge, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let data = response.notification.request.content.userInfo
    let state = UIApplication.shared.applicationState
    DispatchQueue.main.async { // active
        if state == .active {
            PushManager.object().handlePushNotification(data, isCameFromForeground: true)
        } else if state == .background {
            PushManager.object().handlePushNotification(data)
        } else {
            PushManager.object().handlePushNotification(data)
        }
    }
    completionHandler()
} 
...