使用.p8文件后未收到iOS Firebase云消息传递通知 [英] iOS Firebase Cloud Messaging Notifications not being received after using .p8 file

查看:61
本文介绍了使用.p8文件后未收到iOS Firebase云消息传递通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了以下所有步骤,并在 App Delegate 中添加了相应的导入和代码.我还确保我在运行该应用程序时允许接受通知.

按照以下步骤操作,为什么为什么我从Firebase Cloud Messaging Console发送通知后仍无法收到通知?

  1. 在我的开发人员帐户中,我转到了证书,标识符和个人资料

  2. Keys 下,我选择了 All ,然后单击右上角的添加"按钮(+)

  3. Key Description 下,我为签名密钥输入了唯一的名称

  4. Key Services 下,我选择了 APNs 复选框,然后单击 Continue ,然后单击 Confirm

  5. 我复制了 Key ID (在步骤7中使用),然后单击 Download 生成并下载了 .p8 密钥

  6. 我去了 Firebase ,点击了 Gear Icon > Project Settings > Cloud Messaging (不像步骤10那样增长>云消息传递)

  7. iOS应用配置> APNs身份验证密钥下,我转到第一部分 APNs身份验证密钥(没有APNs证书),选择 Upload 并上传 .p8 密钥,密钥ID 和我的 Team ID . teamId 位于 Membership 部分,并且keyId是 xxxxxxx .p8文件的 xxxxxxx 部分.

  8. 在我的Xcode项目中,我转到了 Capabilities > Background Modes ,将其打开 On ,然后选中了 Remote Notifications

  9. 然后我转到> Push Notifications 并将其打开 On ,它会自动为该应用生成一个授权证书(位于内部)项目导航器)

  10. 要在Firebase中发送通知,我去了 Grow > Cloud Messaging > 发送第一条消息> 1.通知文本输入了一些随机字符串> 2.定位,然后选择我的应用的 bundleId > 3.立即计划> 4.按下一步> 5.选择声音徽章> 查看

  11. 在AppDelegate中,我添加了 import UserNotifications import FirebaseMessaging import Firebase ,并注册了 UNUserNotificationCenterDelegate ,并在下面添加了代码.

  12. 要设置

    解决方案

    我认为您也应该将此代码添加到您的代码中,否则您将不会收到推送通知.Firebase现在需要什么apns令牌才能向您发送推送.

      func应用程序(_应用程序:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:Data){Messaging.messaging().apnsToken = deviceToken} 

    I followed all the steps below and added the appropriate imports and code in App Delegate. I also made sure I allowed Notifications to be accepted when I ran the app.

    Following the steps below, why is it that I can't receive the Notifications after I send one from the Firebase Cloud Messaging Console ?

    1. In my Developer account I went to Certificates, Identifiers & Profiles

    2. Under Keys, I selected All and clicked the Add button (+) in the upper-right corner

    3. Under Key Description, I entered a unique name for the signing key

    4. Under Key Services, I selected the APNs checkbox, then clicked Continue then clicked Confirm

    5. I copied the Key ID (used in step 7) and clicked Download to generate and download the .p8 key

    6. I went to Firebase, clicked the Gear Icon > Project Settings > Cloud Messaging (not Grow > Cloud Messaging like step 10)

    7. Under iOS app configuration > APNs Authentication Key I went to the first section APNs Authentication Key (NOT APNs Certificates), selected Upload and uploaded the .p8 key, the Key ID, and my Team Id. The teamId is located in the Membership section and the keyId is the xxxxxxx part of the xxxxxxx.p8 file.

    8. In my Xcode project I went to Capabilities > Background Modes, turned it On, and checked Remote Notifications

    9. Then I went to > Push Notifications and turned it On which automatically generated an Entitlement Certificate for the app (it's inside the project navigator)

    10. To send a notification in Firebase I went to Grow > Cloud Messaging > Send Your First Message > 1. Notification Text entered some random String > 2. Target and selected my app's bundleId > 3. Scheduling Now > 4. pressed Next > 5. selected sound and a badge > Review

    11. In AppDelegate I added import UserNotifications, import FirebaseMessaging, import Firebase, registered for the UNUserNotificationCenterDelegate and added the code below.

    12. To set up the reCAPTCHA verification I went to the Blue Project Icon > Info > URL Types then in the URL Schemes section (press the plus sign + if nothing is there), I entered in the REVERSED_CLIENT_ID from my GoogleService-Info.plist

    I've added break points to all the print statements below and after I send a message from Firebase none of them get hit.

    import UserNotifications
    import FirebaseMessaging
    import Firebase
    
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            FirebaseApp.configure()
    
            UNUserNotificationCenter.current().delegate = self
    
            if #available(iOS 10.0, *) {
    
                UNUserNotificationCenter.current().requestAuthorization(options: [.sound,.alert,.badge]) {
                [weak self] (granted, error) in
    
                    if let error = error {
                        print(error.localizedDescription)
                        return
                    }
    
                    print("Success")
                }
                application.registerForRemoteNotifications()
    
            } else {
    
                let notificationTypes: UIUserNotificationType = [.alert, .sound, .badge]
                let notificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
                application.registerForRemoteNotifications()
                application.registerUserNotificationSettings(notificationSettings)
            }
        }
    
        // MARK:- UNUserNotificationCenter Delegates
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
            Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.unknown)
    
            var token = ""
            for i in 0..<deviceToken.count{
                token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
            }
            print("Registration Succeded! Token: \(token)")
        }
    
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            print("Notifcation Registration Failed: \(error.localizedDescription)")
        }
    
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    
            if let gcm_message_id = userInfo["gcm_message_id"]{
                print("MessageID: \(gcm_message_id)")
            }
    
            print(userInfo)
        }
    
        @available(iOS 10.0, *)
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
            completionHandler(.alert)
    
            print("Handle push from foreground \(notification.request.content.userInfo)")
    
            let dict = notification.request.content.userInfo["aps"] as! NSDictionary
            let d = dict["alert"] as! [String:Any]
            let title = d["title"] as! String
            let body = d["body"] as! String
            print("Title:\(title) + Body:\(body)")
            showFirebaseNotificationAlertFromAppDelegate(title: title, message: body, window: self.window!)
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    
            print("\(response.notification.request.content.userInfo)")
    
            if response.actionIdentifier == "yes"{
                print("True")
            }else{
                print("False")
            }
        }
    
        func showFirebaseNotificationAlertFromAppDelegate(title: String, message: String, window: UIWindow){
            let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: .default, handler: nil)
            alert.addAction(action)
            window.rootViewController?.present(alert, animated: true, completion: nil)
        }
    }
    

    The message gets sent successfully as you can see in the below pic but I never receive it.

    解决方案

    I think you should also add this to your code otherwise you won't be receiving the push notifications. Firebase needs to now what the apns token is to send you the pushes.

        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            Messaging.messaging().apnsToken = deviceToken
        }
    

    这篇关于使用.p8文件后未收到iOS Firebase云消息传递通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆