ios - 如何使用 firebase 获取设备 token ?

标签 ios swift firebase-notifications

在旧项目中,我在第一次安装应用程序或刷新 token 时收到了设备 token 。但是现在我创建了一个新项目并编写了用于注册设备 token 委托(delegate)并请求许可的代码,但是现在在 swift 版本 4.2 中没有调用注册设备 token 。有人遇到过这个问题吗?如果是,解决方案是什么?

import UIKit
import FirebaseInstanceID
import GoogleMaps
import GooglePlaces
import UserNotifications
import FirebaseCore
import FirebaseMessaging
import Alamofire
import Fabric
import Crashlytics

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

    var window: UIWindow?

    let locationManager = CLLocationManager()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        if let statusbar = UIApplication.shared.value(forKey: "statusBar") as? UIView {
            statusbar.backgroundColor = UIColor.fromHexaString(hex: "feac1c")
        }

        UIApplication.shared.statusBarStyle = .lightContent

        Fabric.with([Crashlytics.self])


        let remoteNotif = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? NSDictionary

        if remoteNotif != nil
        {

        }
        else
        {
            print("Not remote")
            UNUserNotificationCenter.current().removeAllDeliveredNotifications()
        }

        GMSServices.provideAPIKey(google_url_links().google_mapKey)
        GMSPlacesClient.provideAPIKey(google_url_links().google_mapKey)



        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

                    Messaging.messaging().delegate = self

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

        application.registerForRemoteNotifications()

        FirebaseApp.configure()




         NotificationCenter.default.addObserver(self, selector: #selector(appDelegate.tokenRefereshNotification), name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        // Override point for customization after application launch.
        return true
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

//    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
//        
//        print("Firebase registration token: \(fcmToken)")
//        UserDefaults.standard.set(fcmToken, forKey: "DeviceToken")
//        
//        
//    }


    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {

        Messaging.messaging().apnsToken = deviceToken
        //FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: .none)
        //   Messaging.messaging().setAPNSToken(deviceToken, type: .sandbox)
    }

    @objc func tokenRefereshNotification()
    {
        let refereshtoken  = InstanceID.instanceID().token() ?? ""

        print("token23123::::\(refereshtoken)")
        UserDefaults.standard.set(refereshtoken, forKey: "deviceToken")
        connectToFCM()
    }

    func connectToFCM()
    {
        guard InstanceID.instanceID().token() != nil else
        {
            return
        }

        Messaging.messaging().disconnect()
        Messaging.messaging().connect { (error) in

            if (error != nil)
            {
                print("error unable to connect\(String(describing: error))")
            }
            else
            {
                print("connect to fcm")
            }
        }
    }



    @objc func CheckInterntConnection()
    {
        let alert = UIAlertController(title: "", message: custom_message().error_internet, preferredStyle: UIAlertController.Style.actionSheet)
        alert.addAction(UIAlertAction(title: custom_message().OK, style: UIAlertAction.Style.default, handler: nil))
        self.window?.rootViewController?.present(alert, animated: true, completion: nil)
    }

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

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

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

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

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


}

最佳答案

您也需要这样做以获得 firebase token

  1. 在您的 AppDelegate 类中声明一个变量。

    var firebaseToken: String = "" 
    
  2. 在您的 didFinishLaunchingWithOptions 函数中调用这些方法

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
        FirebaseApp.configure()
        self.registerForFirebaseNotification(application: application)
        Messaging.messaging().delegate = self
        return true
    }
    
  3. 在您的 AppDelegate 类中添加此函数。

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }
    
    func registerForFirebaseNotification(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 })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
    
        application.registerForRemoteNotifications()
    }
    }
    
  4. 最后创建 AppDelegate 的扩展并添加这些功能

    extension AppDelegate: MessagingDelegate, UNUserNotificationCenterDelegate {
    
    //MessagingDelegate
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        self.firebaseToken = fcmToken
        print("Firebase token: \(fcmToken)")
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("didReceive remoteMessage: \(remoteMessage)")
    }
    
    //UNUserNotificationCenterDelegate
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("APNs received with: \(userInfo)")
    
    
     }
    }
    

关于ios - 如何使用 firebase 获取设备 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56168180/

相关文章:

android - 应用未运行时加载资源的问题

ios - 是否可以只构建一次 Pod?

iphone - 为什么这段代码在 iOS 5.1 中会崩溃,而在 iOS 6 中不会?

arrays - 查询解析数组数据到本地数组,并添加到 TableView (Swift)

swift - SpriteKit : detect if UILongPressGestureRecognizer tapped child node

swift - 使用 Cocoapods 对依赖于 Objective C 项目的 swift 项目进行 Linting 失败

ios - 应用程序在后台运行时的 Firebase 数据库事务 iOS

Android Firebase 推送通知在单击时重新启动应用程序

ios - 使用Podofo更新PDF中的小部件

iphone - Restkit 的链接器错误,找不到 Restkit.framework