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.



But there's a problem. On `iPhone 6`, version `12.4`, you can normally get device tokens and FCM values.



However, `11.4` does not get a device token value, nor does it get an FCM token value. I don't know what the problem is.



AppDelegate.swift

~~~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)
            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)
        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. And the iOS version is the same.**

~~~swift

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

~~~

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. How can you solve this problem?

Accepted Reply

Turned out to be a bug, due to multiple installs and deletions of the app on the iPhone, so a simple iPhone restart fixed the bug, and it was able to register for notifications, and in the end, called the didRegisterForRemoteNotificationsWithDeviceToken delegate method.

Replies

Turned out to be a bug, due to multiple installs and deletions of the app on the iPhone, so a simple iPhone restart fixed the bug, and it was able to register for notifications, and in the end, called the didRegisterForRemoteNotificationsWithDeviceToken delegate method.