FCM推送通知在iOS 11中不起作用 [英] FCM Push notification not working in iOS 11

查看:1491
本文介绍了FCM推送通知在iOS 11中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理推送通知,这是使用较低版本的ios完成的,但在ios 11中从未收到任何推送通知。我使用的是Firebase云消息传递。拜托,任何人都有解决方案然后请分享。

I need to handle push notification and that's done with a lower version of ios but in ios 11 never receive any push notification. I using Firebase Cloud Messaging. please, anyone has a solution then please share.

推荐答案

请检查为

Please Check as

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Use Firebase library to configure APIs
    FirebaseApp.configure()
    self.registerForPushNotifications(application: application)
    Messaging.messaging().delegate = self

    if let token = InstanceID.instanceID().token() {
        NSLog("FCM TOKEN : \(token)")
        DataModel.sharedInstance.onSetUserFCMStringToken(FCM: token)
        self.connectToFcm()
    }
    if launchOptions != nil {
        //opened from a push notification when the app is closed
        _ = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] ?? [AnyHashable: Any]()
    }
    else {
        //opened app without a push notification.
    }
    return true
}

@available(iOS 10 ,*)

@available(iOS 10, *)

extension AppDelegate: UNUserNotificationCenterDelegate {
// iOS10+, called when presenting notification in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    NSLog("[UserNotificationCenter] willPresentNotification: \(userInfo)")
    //TODO: Handle foreground notification
    completionHandler([.alert])
}

// iOS10+, called when received response (default open, dismiss or custom action) for a notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    NSLog("[UserNotificationCenter] didReceiveResponse: \(userInfo)")
    //TODO: Handle background notification
    completionHandler()
}}

extension AppDelegate : MessagingDelegate {
//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    NSLog("[RemoteNotification] didRefreshRegistrationToken: \(fcmToken)")
}

// Receive data message on iOS 10 devices while app is in the foreground.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    NSLog("remoteMessage: \(remoteMessage.appData)")
}}

//Register for push notification.
func registerForPushNotifications(application: UIApplication) {
    if #available(iOS 10.0, *) {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
            if error == nil{
                DispatchQueue.main.async(execute: {
                    application.registerForRemoteNotifications()
                })
            }
        }
    }
    else {

        let settings = UIUserNotificationSettings(types: [.alert,.sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    // Add observer for InstanceID token refresh callback.
    NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

}

@objc func tokenRefreshNotification(_ notification: Notification) {
    print(#function)
    if let refreshedToken = InstanceID.instanceID().token() {
        NSLog("Notification: refresh token from FCM -> \(refreshedToken)")

    }
    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        NSLog("FCM: Token does not exist.")
        return
    }

    Messaging.messaging().shouldEstablishDirectChannel = true
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    NSLog("Notification: Unable to register for remote notifications: \(error.localizedDescription)")
}


// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {


    Messaging.messaging().apnsToken = deviceToken


}

// iOS9, called when presenting notification in foreground
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    NSLog("didReceiveRemoteNotification for iOS9: \(userInfo)")

}

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




}

这篇关于FCM推送通知在iOS 11中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆