【问题标题】:How can I get the token from Firebase Cloud Messaging on iOS如何从 iOS 上的 Firebase Cloud Messaging 获取令牌
【发布时间】:2018-03-11 22:17:57
【问题描述】:

Podfile

target 'T' do
  use_frameworks!

  pod 'Firebase/Core'
  pod 'Firebase/Messaging'
  pod ‘Firebase’
  pod ‘Firebase/Auth’
  pod 'Firebase/Database'
  pod 'Firebase/Storage'
end

AppDelegate.swift 中的导入

import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseMessaging

AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate

运行 Xcode 9.2,编译语言版本 swift 4,部署目标 11.2

根据文档https://firebase.google.com/docs/cloud-messaging/ios/client 我应该可以使用以下内容

1) Messaging.messaging().delegate = self
2) func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
   print("Firebase registration token: \(fcmToken)")
 }

3) FIRMessageDelegate

但是 xcode 无法识别 - 来自 1) 的“消息传递”类 -'FIRMessageDelegate' 来自 3) - 或 2) 中的委托方法

因为我无法获得我的应用所需的 fcmtoken

Xcode 可以识别这些,但这些不在文档中,所以我不知道该怎么做

4) FIRMessagingDelegate
5) FIRMessaging.messaging().remoteMessageDelegate = self

4) 中唯一的委托方法是

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage)
    {
        print(remoteMessage.appData)
    }

我的问题是:如何获得令牌?文档似乎已经过时了。

podfile.lock

PODS:
  - Firebase (3.15.0):
    - Firebase/Core (= 3.15.0)
  - Firebase/Auth (3.15.0):
    - Firebase/Core
    - FirebaseAuth (= 3.1.1)
  - Firebase/Core (3.15.0):
    - FirebaseAnalytics (= 3.7.0)
    - FirebaseCore (= 3.5.2)
  - Firebase/Database (3.15.0):
    - Firebase/Core
    - FirebaseDatabase (= 3.1.2)
  - Firebase/Messaging (3.15.0):
    - Firebase/Core
    - FirebaseMessaging (= 1.2.2)
  - Firebase/Storage (3.15.0):
    - Firebase/Core
    - FirebaseStorage (= 1.1.0)
  - FirebaseAnalytics (3.7.0):
    - FirebaseCore (~> 3.5)
    - FirebaseInstanceID (~> 1.0)
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseAuth (3.1.1):
    - FirebaseAnalytics (~> 3.7)
    - GoogleToolboxForMac/NSDictionary+URLArguments (~> 2.1)
    - GTMSessionFetcher/Core (~> 1.1)
  - FirebaseCore (3.5.2):
    - GoogleToolboxForMac/NSData+zlib (~> 2.1)
  - FirebaseDatabase (3.1.2):
    - FirebaseAnalytics (~> 3.7)
  - FirebaseInstanceID (1.0.9)
  - FirebaseMessaging (1.2.2):
    - FirebaseAnalytics (~> 3.7)
    - FirebaseInstanceID (~> 1.0)
    - GoogleToolboxForMac/Logger (~> 2.1)
    - Protobuf (~> 3.1)
  - FirebaseStorage (1.1.0):
    - FirebaseAnalytics (~> 3.7)
    - GTMSessionFetcher/Core (~> 1.1)
  - GoogleToolboxForMac/DebugUtils (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - GoogleToolboxForMac/Defines (2.1.1)
  - GoogleToolboxForMac/Logger (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - GoogleToolboxForMac/NSData+zlib (2.1.1):
    - GoogleToolboxForMac/Defines (= 2.1.1)
  - GoogleToolboxForMac/NSDictionary+URLArguments (2.1.1):
    - GoogleToolboxForMac/DebugUtils (= 2.1.1)
    - GoogleToolboxForMac/Defines (= 2.1.1)
    - GoogleToolboxForMac/NSString+URLArguments (= 2.1.1)
  - GoogleToolboxForMac/NSString+URLArguments (2.1.1)
  - GTMSessionFetcher/Core (1.1.9)
  - Protobuf (3.2.0)

【问题讨论】:

    标签: ios swift firebase-cloud-messaging


    【解决方案1】:

    在 appdelegate 中试试这个

    import UIKit
    import Firebase
    import UserNotifications
    
    
    
    
    
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {
    
        var window: UIWindow?
        var fcmTokenUser : String?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            FirebaseApp.configure()
    
    
            print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String)
    
    
            // To get FCM token that will be sent to APNS via Google FCM
            if #available(iOS 10.0, *) {
                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    
                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()
    
    
            Messaging.messaging().delegate = self
            let token = Messaging.messaging().fcmToken
    
    
    
    
    
            return true
        }
    
    
    
        func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String){
             // This callback is fired at each app startup (when the user install the app for the very first time) and whenever a new token is generated due to The app is restored on a new device, The user uninstalls/reinstall the app, The user clears app data.
    
            // after fcm generated for the very first time,then fcm can also be retrieved in the 'didFinishLaunchingWithOptions' method above (let token = Messaging.messaging().fcmToken)
    
    
            fcmTokenUser = fcmToken
    
    
    
    
    
    
        }
    
    
        private func application(application: UIApplication,
                         didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
            Messaging.messaging().apnsToken = deviceToken as Data
        }
    
    
    
    
    
    }
    

    pod 文件

    # Uncomment the next line to define a global platform for your project
    platform :ios, '9.0'
    
    target  do
      # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
      use_frameworks!
    
      # Pods for HRIS
    
     pod 'Firebase/Core'
     pod 'Firebase/Messaging'
     pod 'FirebaseInstanceID'
    
    
    
    
    
    
    end
    

    【讨论】:

    • 没有改变仍然无法识别
    • 您使用的是最新版本的 Firebase 吗?看来您安装的是 Firebase 3 而不是 4,据我所知,最新的 Firebase 协议和类将不再使用 FIR 前缀,只需使用 MessagingDelegate 而不是 FIRMessagingDelegate
    【解决方案2】:

    解决方案是 pod install 安装的是旧版本的 firebase。最新版本是 4,但 pod install 正在安装版本 3。所以要修复,我需要进行 pod 更新,但命令说无法连接到 gitbub,所以我做了这个人在这里做的 Cocoapods: Failed to connect to GitHub to update the CocoaPods/Specs specs repo 然后 pod更新成功,firebase 已升级

    【讨论】:

      【解决方案3】:

      前段时间,我刚刚成功获得了 fcm 令牌,并从 firebase 控制台向我的手机发送了通知。这是 AppDelegage 的完整代码。 firebase.com 文档中的代码似乎已经过时了。

      import UIKit
      import Firebase
      import UserNotifications
      import FirebaseMessaging
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate {
      
      var window: UIWindow?
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions 
      launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          // Override point for customization after application launch.
      
          FirebaseApp.configure()
      
      
          if #available(iOS 10.0, *) {
              let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
              UNUserNotificationCenter.current().requestAuthorization(
                  options: authOptions,
                  completionHandler: {_,_ in })
      
              // For iOS 10 display notification (sent via APNS)
              UNUserNotificationCenter.current().delegate = self as! 
      UNUserNotificationCenterDelegate
              // For iOS 10 data message (sent via FCM)
              Messaging.messaging().delegate = self as! MessagingDelegate
          }
      
          application.registerForRemoteNotifications()
      
          return true
          }
      }
      
      func application(_ application: UIApplication, 
      didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
      Messaging.messaging().apnsToken = deviceToken
      
      
      }
      
      
      
      
      
      
      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:.
      }
      
      
      @available(iOS 10, *)
      extension AppDelegate : UNUserNotificationCenterDelegate {
      
      // Receive displayed notifications for iOS 10 devices.
      
      func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent 
      notification: UNNotification, withCompletionHandler completionHandler: 
      @escaping (UNNotificationPresentationOptions) -> Void) {
          let userInfo = notification.request.content.userInfo
          // Print message ID.
          print("Message ID: \(userInfo["gcm.message_id"]!)")
      
          // Print full message.
          print("%@", userInfo)
      
      }
      
      }
      
      extension AppDelegate : MessagingDelegate {
      // Receive data message on iOS 10 devices.
      func applicationReceivedRemoteMessage(_ remoteMessage: 
      MessagingRemoteMessage) {
          print("%@", remoteMessage.appData)
      }
      
      func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: 
      String){
      
          print("token: \(fcmToken)")
      
      
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-12
        • 2017-11-08
        • 2017-05-29
        • 1970-01-01
        • 1970-01-01
        • 2019-09-08
        • 2018-11-15
        • 2016-09-24
        相关资源
        最近更新 更多