【问题标题】:iOS Firebase push notification not working but working on pusheriOS Firebase 推送通知不起作用但在推送器上工作
【发布时间】:2019-06-04 22:41:52
【问题描述】:

问题:

鉴于我能够接收设备令牌和 firebase 令牌,因此无法从 firebase 接收推送通知。

这是我在AppDelegate.swift 中的主要电话

UIApplication.shared.registerForRemoteNotifications()

此调用成功,我能够建立与 APNS 的连接,因为我能够通过此调用获取我的令牌:

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

另外,我知道我正在连接到 firebase,因为我可以通过此调用获取我的 firebase 令牌:

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String)

所以我很有信心我在AppDelegate.swift 中的代码很好。

以下是我配置 Firebase 推送通知的步骤:

  1. 下载我的 google-service.plist 文件并将其拖到我的项目中
  2. 登录到我的苹果开发者帐户(付费)并创建带有推送通知的密钥(复制密钥 ID 以及我的团队 ID 或应用前缀)。
  3. 进入我的 firebase 帐户并上传我的密钥以及我的 KeyID 和 TeamID
  4. 我确保我的应用功能已将推送通知开关设为 ON
  5. 尝试发送测试消息,但应用从未收到任何消息

我的 AppDelegate.swift:

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        FirebaseApp.configure()
        
        UIApplication.shared.applicationIconBadgeNumber = 0
        // Override point for customization after application launch.
        loggingWithSwitftyBeaverConfiguration()
        
        UNUserNotificationCenter.current().delegate = self
        
        // requesting user's permission to accpet push notification
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            
            if granted == true {
                log.debug("User granted push notification")
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            } else {
                log.debug("User did not grant pn")
            }
        }
        return true
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        log.debug("Device token receiving failed because: \(error.localizedDescription)")
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        let token = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
        log.debug("Token: \(token)")
    }
    
    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        log.debug("\(remoteMessage.description)")
    }
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        log.debug("Firebase cloud messaging token: \(fcmToken)")
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        Messaging.messaging().shouldEstablishDirectChannel = true
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        Messaging.messaging().shouldEstablishDirectChannel = false
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        UIApplication.shared.applicationIconBadgeNumber += 1
        
        print("push notification received")

    }
    
}

额外信息:我可以使用推送器接收测试通知,只是想把它扔出去,

谢谢

更新:-工作代码:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var compositionRoot: CompositionRoot?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        window = UIWindow()
        configureCompositionRoot()
        configureFirebase()
        configurePushNotification()
        configureApplicationEntryPoint()
        configureLogging()
        
        return true
    }
    
    func configureCompositionRoot() {
        
        guard let window = window else { return }
        compositionRoot = CompositionRoot(window: window)
    }

    func configureApplicationEntryPoint() {
        
        guard let compositionRoot = compositionRoot else { return }
        compositionRoot.getCoordinator().onStart()
    }
    
    func configureLogging() {
        let console = ConsoleDestination()
        log.addDestination(console)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        let token = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
        print("Token: \(token)")
        Messaging.messaging().apnsToken = deviceToken
        
        //Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.prod)
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func configureFirebase() {
        FirebaseApp.configure()
    }
    
    func configurePushNotification() {
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (granted, error) in
            
            if granted == true {
                print("User granted push notification")
                UNUserNotificationCenter.current().delegate = self
                Messaging.messaging().delegate = self
                
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
                
            } else {
                print("User did not grant pn")
            }
        }
    }
}

extension AppDelegate: MessagingDelegate {
    
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    }
    
}

【问题讨论】:

  • 您尝试从哪里发送推送通知?
  • 关于 Firebase 云消息传递
  • 你可以从这里appcoda.com/firebase-push-notifications检查所有步骤,也许你可以找到缺少的东西
  • 我也试过这个方法,不适合我
  • 尝试添加 --> func applicationDidBecomeActive(application: UIApplication) { FIRMessaging.messaging().connectWithCompletion { error in print(error) } }

标签: swift firebase apple-push-notifications


【解决方案1】:

请检查您的有效载荷。这可能是您没有收到通知的原因。 你的有效载荷应该是:

{
    "to": "APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",
    "notification": {
        "body": "great match!",
        "title": "Portugal vs. Denmark",
        "icon": "myicon"
    },
    "data": {
        "Nick": "Mario",
        "Room": "PortugalVSDenmark"
    }
}

即使 Firebase 由于转发的 APNS 有效负载不正确而返回成功请求,在数据下拥有所有数据也不会触发 iOS 中的任何通知。此外,正确的方法应该是遵循 GCM 或 FCM 有效负载建议,即对通知消息使用通知,对自定义键/值对使用数据。

当 FCM 向 APNS 发送数据时,它会将其转换为 APNs 有效负载。它在 aps 标签中设置通知的值,即

{
    "aps" : {
        "alert" : {
            "title" : "Portugal vs. Denmark",
            "body" : "Portugal vs. Denmark",
        }
    },
    "Nick" : "Mario",
    "Room" : "PortugalVSDenmark"
}

【讨论】:

  • 嗨 - 感谢 18 个月前提供的这个有用的答案 :) 你将如何适应 Android 应用程序,这些应用程序确实需要标题和正文出现在数据中才能显示应用程序何时在背景?
【解决方案2】:

[按照此处定义的分步流程进行操作..]

https://firebase.google.com/docs/cloud-messaging/ios/client

【讨论】:

    【解决方案3】:

    另一个可能的原因是禁用 Firebase Swizzling,如下所述: https://firebase.google.com/docs/cloud-messaging/ios/client

    【讨论】:

    • 我已经阅读了有关方法调配的文章,但我对它在做什么以及如何禁用它会解决问题一无所知,请解释一下,谢谢
    • Swizzling 是一种 ObjectiveC 语言功能,用于在运行时用另一个方法的实现替换一个方法的实现,Firebase 出于多种原因使用它,并且由于我们没有 Firebase SDK 的源代码,所以我们不能确切地说,希望他们提供一种方法来禁用它,如链接文档中所述。
    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多