【问题标题】:How to call API when app is terminated in push notifcation iOS Swift?当应用程序在推送通知iOS Swift中终止时如何调用API?
【发布时间】:2019-06-11 16:11:57
【问题描述】:

我们正在处理推送通知。当我们在活动、后台、前台和终止中收到通知时,我们需要调用 Web 服务。但是当我们终止应用程序时,我们会收到通知,但无法调用 Web 服务。调用 Web 服务的原因是为了确定收到的消息是针对移动应用的。

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

还有其他方法可以识别消息是在服务器端的移动应用中传递的吗?

【问题讨论】:

    标签: ios swift firebase push-notification


    【解决方案1】:

    根据 Apple 指南,您可以在后台和前台状态下获得推送通知,但是当涉及到 终止状态苹果不允许您自动打开应用程序或 进行任何类型的操作,除非您通过通知启动应用程序。

    虽然您可以在应用启动时使用启动选项在 Terminated 状态下处理通知。

    编码示例:

    在您的 AppDelegate.swift 中导入 firebase 库

    import Firebase
    import FirebaseInstanceID
    import FirebaseMessaging
    import UserNotifications
    

    每当应用启动注册推送通知服务时,将以下代码行添加到您的 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)
        }
    
    }
    

    使用notificationCenter的以下方法来处理前台和后台状态的通知:

    // 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...
            }
        }
    }
    

    【讨论】:

    • 我不想在打开应用程序时收到通知。我想在它处于非活动状态时收到通知。
    • @HarikarthickK 你所说的非活动状态是什么意思,不管它是杀死状态还是背景??
    • @HarikarthickK 我正在更新我的答案它肯定会帮助你在被杀状态下获得通知。您是否使用 Firebase 进行通知??
    • @HarikarthickK 看看我已经更新了我的答案。它是,特别是对于火力基地。我在我的应用程序中使用了它。它工作正常
    • @HarikarthickK 不要忘记在您的应用功能中添加背景模式。
    【解决方案2】:

    我们在链接下方有一个名为静默通知检查的选项 https://medium.com/@m.imadali10/ios-silent-push-notifications-84009d57794c

    【讨论】:

    • 我们可以在终止状态下处理静默推送吗?如果是,那么如何?
    【解决方案3】:

    检查下面的链接,这是您需要的。

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

    您需要为推送通知激活后台模式。完整的过程在上面的文章中已经解释过了。

    【讨论】:

    • 这篇文章已经过时了,因为 2016 年包含了服务扩展
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2020-09-12
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多