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

时间:2019-10-02 04:50:59

标签: ios swift firebase firebase-cloud-messaging

我正在通过FCM开发消息通信。

但是有一个问题。在$sql = "SELECT * FROM articles WHERE ID='".$id."'"; $result5 = mysqli_query($link, $sql); if (mysqli_num_rows($result5) > 0) { while($row = mysqli_fetch_assoc($result5)) { $aa = $row[]; array_push($aa, $a) } print_r($aa); } 版本iPhone 6上,通常可以获取设备令牌和FCM值。

但是,12.4没有获得设备令牌值,也没有获得FCM令牌值。我不知道问题是什么。

AppDelegate.swift

11.4

在iPhone 12.4上,此处接收FCM令牌值。和iOS版本相同。

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()
    }

Podfile

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
    }

iPhone日志中的11.4

# 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'

但是,在iPhone 11.4的任何地方都看不到FCM令牌或设备令牌值的日志。您如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

@Starsky是正确的。这是一个错误,当我删除我的应用程序并重新启动设备后,问题得以解决。