简体   繁体   English

为什么在 iOS 11.4 版本中无法获取设备令牌值和 FCM 令牌值?

[英]Why can't I get the device token value and FCM token value in iOS version 11.4?

I am developing message communication through FCM.我正在通过 FCM 开发消息通信。

But there's a problem.但是有一个问题。 On iPhone 6 , version 12.4 , you can normally get device tokens and FCM values.iPhone 6版本12.4上,您通常可以获取设备令牌和 FCM 值。

However, 11.4 does not get a device token value, nor does it get an FCM token value.但是, 11.4没有获得设备令牌值,也没有获得 FCM 令牌值。 I don't know what the problem is.我不知道问题是什么。

AppDelegate.swift AppDelegate.swift

import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate  {

    func registerAppForPushNotificaition(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
            let categories = NSSet(objects: inviteCategory)

            center.delegate = self
            center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
            center.requestAuthorization(options: [.sound, .badge, .alert], completionHandler: { (granted, error) in
                if !(error != nil){
                    DispatchQueue.main.async(execute: {
                        UIApplication.shared.registerForRemoteNotifications()
                    })
                }
            })
        } else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound , .alert , .badge] , categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler(.alert)
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        // Override point for customization after application launch.
        //create the notificationCenter
        Messaging.messaging().delegate = self
        FirebaseApp.configure()

        //Register App For Push Notification
        let center = UNUserNotificationCenter.current()
        let inviteCategory = UNNotificationCategory(identifier: "Notification", actions: [], intentIdentifiers: [], options: UNNotificationCategoryOptions.customDismissAction)
        let categories = NSSet(objects: inviteCategory)

        center.delegate = self
        center.setNotificationCategories(categories as! Set<UNNotificationCategory>)
        DispatchQueue.main.async(execute: {
            UIApplication.shared.registerForRemoteNotifications()
        })
        application.registerForRemoteNotifications()
  }

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
        Log.Info("Registration succeeded!")
        Log.Info("Token: \(token)")
        Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                Log.Error("Error fetching remote instance ID: \(error)")
            } else if let result = result {
                Log.Info("Remote instance ID token: \(result.token)")
                LocalStorage.set(result.token, "dacDeviceToken")
            }
        }
        Messaging.messaging().shouldEstablishDirectChannel = true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        Messaging.messaging().apnsToken = deviceToken as Data
        // print(deviceToken)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        Log.Warning("Registration failed!")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if Auth.auth().canHandleNotification(userInfo) {
            Log.Info("fetchCompletionHandler")
            completionHandler(UIBackgroundFetchResult.noData)
            return
        }
        Log.Info("fetchCompletionHandler")
        completionHandler(UIBackgroundFetchResult.newData)
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        Log.Info("fcmToken \(fcmToken)")
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        Log.Info("remort \(remoteMessage.appData)")
    }


    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        Log.Info("applicationWillResignActive")
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        Log.Info("applicationDidEnterBackground")
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        Log.Info("applicationWillEnterForeground")
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        Log.Info("applicationDidBecomeActive")
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        Log.Info("applicationWillTerminate")
    }

    func getNotificationSettings() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            print("Notification settings: \(settings)")
            guard settings.authorizationStatus == .authorized else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    @available(iOS 10, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let data = response.notification.request.content.userInfo

        Log.Info(data)
        guard
            let aps = data[AnyHashable("aps")] as? NSDictionary,
            let alert = aps["alert"] as? NSDictionary,
            let body = alert["body"] as? String
            else {
                Log.Error("it's not good data")
                return
        }

        completionHandler()
    }

On iPhone 12.4, FCM token values are received here.在 iPhone 12.4 上,在此处接收 FCM 令牌值。 And the iOS version is the same.和iOS版本相同。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map{ String(format: "%02x", $0) }.joined()
        Log.Info("Registration succeeded!")
        Log.Info("Token: \(token)")
        Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox)
        Messaging.messaging().apnsToken = deviceToken
        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                Log.Error("Error fetching remote instance ID: \(error)")
            } else if let result = result {
                Log.Info("Remote instance ID token: \(result.token)")
                LocalStorage.set(result.token, "dacDeviceToken")
            }
        }
        Messaging.messaging().shouldEstablishDirectChannel = true
    }

Podfile播客文件

# Pods for DeleteMe
pod 'SwiftSVG', '~> 2.0'
pod 'Toaster'
pod 'BigInt', '~> 4.0'
pod 'CryptoSwift'
pod 'RealmSwift'
pod 'web3.swift.pod', '~> 2.2.0'
pod 'Firebase'
pod 'Firebase/Messaging'
pod 'Firebase/Auth'

11.4 in Iphone Log 11.4 在 Iphone 日志中

2019-10-02 13:39:01.964008+0900 test[1804:476574]  - <AppMeasurement>[I-ACS036002] Analytics screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable screen reporting, set the flag FirebaseScreenReportingEnabled to NO (boolean) in the Info.plist
2019-10-02 13:39:02.045557+0900 test[1804:476574] 6.9.0 - [Firebase/Core][I-COR000003] The default Firebase app has not yet been configured. Add `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) to your application initialization. Read more:
2019-10-02 13:39:02.099986+0900 test[1804:476574] 6.9.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60102000 started
2019-10-02 13:39:02.102201+0900 test[1804:476574] 6.9.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled 
2019-10-02 13:39:02.139092+0900 test[1804:476582] 6.9.0 - [Firebase/Messaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
to ensure proper integration.
2019-10-02 13:39:02.231208+0900 test[1804:476536] [Graphics] UIColor created with component values far outside the expected range. Set a breakpoint on UIColorBreakForOutOfRangeColorComponents to debug. This message will only be logged once.
INFO: 2019-10-02 04:39:02 +0000 - <UI> AppDelegate.swift applicationDidBecomeActive(_:) [Line:225] 
applicationDidBecomeActive
2019-10-02 13:39:02.371104+0900 test[1804:476581] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2019-10-02 13:39:02.373237+0900 test[1804:476581] [MC] Reading from public effective user settings.

However, you can't see logs of FCM Token or device token values anywhere on iPhone 11.4.但是,您在 iPhone 11.4 上的任何地方都看不到 FCM 令牌或设备令牌值的日志。 How can you solve this problem?你怎么能解决这个问题?

@Starsky was right. @Starsky 是对的。 This was a bug, and after I erased my app and restarted the device, the problem was solved.这是一个错误,在我删除我的应用程序并重新启动设备后,问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM