Как вызвать API, когда приложение завершено в push-уведомлении iOS Swift? - PullRequest
0 голосов
/ 17 января 2019

Мы работаем над push-уведомлениями. Нам нужно вызвать веб-сервис, когда мы получим уведомление в активном, фоновом режиме, на переднем плане и завершено. Но когда мы закрыли приложение, мы получили уведомление, но не смогли вызвать веб-сервис. Причиной вызова веб-службы является идентификация сообщения, полученного для мобильного приложения.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if ( application.applicationState == .inactive || application.applicationState == .background ) {
                **// Need to call API**
        }
    }

Есть ли другой способ определить, что сообщение доставлено в мобильном приложении на стороне сервера?

Ответы [ 3 ]

0 голосов
/ 17 января 2019

Проверьте ссылку ниже, это то, что вам нужно.

https://samwize.com/2015/08/07/how-to-handle-remote-notification-with-background-mode-enabled/

Вам нужно активировать фоновый режим для push-уведомлений. Полный процесс описан в статье выше.

0 голосов
/ 12 февраля 2019

У нас есть опция, называемая молчаливым уведомлением. https://medium.com/@m.imadali10/ios-silent-push-notifications-84009d57794c

0 голосов
/ 17 января 2019

В соответствии с рекомендациями Apple вы можете получать push-уведомления как для фона, так и для состояния переднего плана, но когда дело доходит до Завершение состояния Apple не позволяет автоматически открывать приложение или выполнять любые операции, если вы не запускаете приложение через уведомление.

Несмотря на то, что вы можете обрабатывать уведомления в состоянии «Завершено», используя параметры запуска во время запуска приложения.

Пример кодирования:

В вашей библиотеке импорта баз данных AppDelegate.swift

import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

Всякий раз, когда запускается регистрация приложения для службы push-уведомлений, добавьте следующие строки кода в didFinishLaunchingWithOptions

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    registerForPushNotifications(application: application)
    handleNotificationWhenAppIsKilled(launchOptions)
    return true
}

func handleNotificationWhenAppIsKilled(_ launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
    // Check if launched from the remote notification and application is close
    if let remoteNotification = launchOptions?[.remoteNotification] as?  [AnyHashable : Any] {
        // Handle your app navigation accordingly and update the webservice as per information on the app.
    }
}

Добавить методы расширения appDelegate для регистрации удаленного уведомления и получения токена устройства из APNS

//MARK: - Notifications related...
extension AppDelegate {
    func registerForPushNotifications(application: UIApplication) {
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            // For iOS 10 data message (sent via FCM
            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        let savedAPNSToken = UserDefaults.standard.object(forKey: "savedAPNSToken") as? String
        if savedAPNSToken != token {
            UserDefaults.standard.set(token, forKey: "savedAPNSToken")
            UserDefaults.standard.synchronize()
            Messaging.messaging().apnsToken = deviceToken
        }
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error.localizedDescription)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        completionHandler(UIBackgroundFetchResult.newData)
    }

}

Используйте следующие методы Центр уведомлений для обработки уведомлений в основном и фоновом состояниях:

// MARK: - UNUserNotificationCenterDelegate
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        completionHandler([.alert])
    }


    /// Handle tap on the notification banner
    ///
    /// - Parameters:
    ///   - center: Notification Center
    ///   - response: Notification response
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        let userInfo = response.notification.request.content.userInfo
        completionHandler()
    }

Обновление токена Firebase:

extension AppDelegate : MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        // Note: This callback is fired at each app startup and whenever a new token is generated.
        let savedFCMToken = UserDefaults.standard.object(forKey: "savedFCMToken") as? String
        if savedFCMToken != fcmToken {
            UserDefaults.standard.set(fcmToken, forKey: "savedFCMToken")
            UserDefaults.standard.synchronize()
            // Update FCMToken to server by doing API call...
        }
    }
}
...