Firebase - 推送通知 - 不工作

Posted

技术标签:

【中文标题】Firebase - 推送通知 - 不工作【英文标题】:Firebase - Push Notifications - Not working 【发布时间】:2018-11-27 09:20:33 【问题描述】:

我只是在尝试使用 Firebase 推送通知;作为开始,我遵循了这个文件: https://www.appcoda.com/firebase-push-notifications/

这里是我此时的相关代码: (它构建没有任何问题)

......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
    ......
    UNUserNotificationCenter.current().delegate = self
    let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: _, _ in )
    application.registerForRemoteNotifications()
    FirebaseApp.configure()
    ......

    return true


......

// The callback to handle data message received via FCM for devices running ios 10 or above.
func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) 
    print(#function)
    print(remoteMessage.appData)

当我尝试测试它时(按照前面提到的文档中的建议),函数 applicationReceivedRemoteMessage() 永远不会被调用,我看不到任何事情发生。我错过了什么?有什么我应该先看的吗?

有关信息,我使用的是 Xcode 10.1、iOS 12.1 和 Swift 4.2。

【问题讨论】:

您是否在 Firebase 控制台的项目设置中添加了 .p12 证书? 是的,我做到了,一切看起来都很好。 你用func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)方法检查了吗? 取得一些进展后,我在另一篇文章中重新提出了修改后的问题:***.com/questions/53512234/… 【参考方案1】:

检查以下代码:

import Firebase
import UserNotifications

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

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
     setupFireBase(application)


func setupFireBase(_ application: UIApplication) 
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

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


func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) 
    print("Firebase registration token: \(fcmToken)")
    print(messaging)
    ClassUserDefault.shared.deviceToken = fcmToken
    let dataDict: [String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
    connectToFcm()


// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) 
    InstanceID.instanceID().instanceID  (result, error) in
        if let error = error 
            print("Error fetching remote instange ID: \(error)")
         else if let result = result 
            print("Remote instance ID token: \(result.token)")
        
    
    connectToFcm()


func connectToFcm() 
    InstanceID.instanceID().instanceID  (result, error) in
        if let _ = error 
            return
         else if let result = result 
            print("Remote instance ID token: \(result.token)")
        
    


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


public func application(received remoteMessage: MessagingRemoteMessage) 
    print(remoteMessage.appData)


@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) 
    completionHandler([UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge])
    print("Handle push from background or closed")
    print("\(notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: notification.request.content.userInfo)
    //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

    if notification.request.content.userInfo.isEmpty 
        return
     else 
    
    print(_ResponsePush)


@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) 
    print("Handle push from background or closed")
    print("\(response.notification.request.content.userInfo)")
    let _ResponsePush = ClassResponsePush(fromData: response.notification.request.content.userInfo)
    if response.notification.request.content.userInfo.isEmpty  return  else 
        handlePush(userInfo: _ResponsePush)
    
    print(_ResponsePush)


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) 
    let chars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
    var token = ""
    for i in 0..<deviceToken.count 
        token += String(format: "%02.2hhx", arguments: [chars[i]])
    
    print("Device Token = ", token)


func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) 
    print("Received data message: \(remoteMessage.appData)")


func handlePush(userInfo: ClassResponsePush) 



不要忘记在 Firebase 控制台的项目设置的云消息传递中添加 .p12 文件。

希望对你有帮助:)

【讨论】:

我看了你的代码,我有两个问题:ClassUserDefault 和 ClassResponsePush 来自哪里? 两者都是单例类,一类是用户默认保存令牌,而类responsepush是即将到来的响应的响应处理程序,与可编码的相同。明天我会为你提供这两个课程的代码。 取得一些进展后,我在另一篇文章中重新提出了修改后的问题:***.com/questions/53512234/…【参考方案2】:

你好,米歇尔,

根据您的参考链接,您似乎错过了这一行

FIRMessaging.messaging().remoteMessageDelegate = self
   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 )
        // For iOS 10 data message (sent via FCM
        FIRMessaging.messaging().remoteMessageDelegate = self
     else 
        let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
          application.registerUserNotificationSettings(settings)
    

    application.registerForRemoteNotifications()

    FIRApp.configure()

【讨论】:

确实我已经注释掉了这一行,因为它会产生一个错误:“'Messaging' 类型的值没有成员'remoteMessageDelegate'” @Michel 请检查您关注的链接appcoda.com/firebase-push-notifications @Michel 你也可以在这里查看....***.com/questions/51685040/…

以上是关于Firebase - 推送通知 - 不工作的主要内容,如果未能解决你的问题,请参考以下文章

iOS 空 Firebase 推送通知不显示

Firebase - 推送通知 - 没有按预期工作

Firebase 推送通知如何在 IOS 上工作?

使用 FCM 推送通知不工作 iOS

应用程序关闭时 Firebase 推送通知不起作用

Firebase FCM 推送通知停止工作 iOS 11.1.1