当前位置: 首页 > 知识库问答 >
问题:

iOS设备上未显示Firebase云消息通知(前台和后台)

郭德惠
2023-03-14

我正在使用FCM为我的iOS应用程序创建和发送推送通知。

开发环境:

>

  • Xcode 11.3

      null

    问题:

    在遇到问题之前,我设置了我的应用程序,使其能够在应用程序处于后台和前台时接收通知。我对自己非常高兴,我promise了代码。在此之后,我无法在前台或后台接收通知。无论使用的通知是从云消息仪表板还是邮递员发送的,我都收到一个成功的响应但通知从未出现。

    起初,我认为我可能已经达到通知配额,但现在是2天后的事实。

      null

    AppDelegate.Swift

    import UIKit
    import Firebase
    import FBSDKCoreKit
    import GoogleMaps
    import SwiftLocation
    import GooglePlaces
    import Crashlytics
    import GoogleSignIn
    import Armchair
    import UserNotifications
    import FirebaseMessaging
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
        var window: UIWindow?
        var swipeNavigationViewController: SwipeNavigationViewController!
    
        override init() {
            super.init()
    
            FirebaseApp.configure()
    
            Database.database().isPersistenceEnabled = true
            swipeNavigationViewController = SwipeNavigationViewController()
        }
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool  {
            FirebaseConfiguration.shared.setLoggerLevel(.error)
            ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
    
            // Google Maps
            GMSServices.provideAPIKey(FireBaseConstants.GoogleAPIKey)
            GMSPlacesClient.provideAPIKey(FireBaseConstants.GoogleAPIKey)
            GeocoderRequest.GoogleOptions(APIKey: FireBaseConstants.GoogleAPIKey)
    
            let navigationViewController = UINavigationController(rootViewController: swipeNavigationViewController)
            navigationViewController.setNavigationBarHidden(true, animated: false)
    
            self.window?.rootViewController = navigationViewController
            self.window?.makeKeyAndVisible()
    
            showAlertIfPointedTowardProductionDatabase()
            setupReviewRequest()
    
            UIApplication.shared.registerForRemoteNotifications()
    
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
                // If granted comes true you can enabled features based on authorization.
                guard granted else { return }
                DispatchQueue.main.async {
                    print("UserID: \(UserManager.sharedManager.currentUser?.userID)")
                    let pushManager = PushNotificationManager(userID: "currently_logged_in_user_id")
                    pushManager.registerForPushNotifications()
                }
            }
    
            UNUserNotificationCenter.current().delegate = self
    
            return true
        }
    
        func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
            let handledByFB = ApplicationDelegate.shared.application(app, open: url, options: options)
    
            var handledByGoogle = false
            if !handledByFB {
                handledByGoogle = GIDSignIn.sharedInstance().handle(url)
            }
    
            let handled = handledByFB || handledByGoogle
    
            return handled
        }
    
        private func setupReviewRequest() {
            //Code...
        }
    
        // This method will be called when app received push notifications in foreground
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.alert, .badge, .sound])
        }
    }
    

    PushNotificationManager.Swift

    import Foundation
    import Firebase
    import FirebaseFirestore
    import FirebaseMessaging
    import UIKit
    import UserNotifications
    
    class PushNotificationManager: NSObject, MessagingDelegate, UNUserNotificationCenterDelegate {
    
        let userID: String
        let gcmMessageIDKey = "gcm.message_id"
    
        init(userID: String) {
            self.userID = userID
            super.init()
        }
    
        func registerForPushNotifications() {
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
    
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (_, error) in
                guard error == nil else{
                    print(error!.localizedDescription)
                    return
                }
            }
    
            //get application instance ID
            InstanceID.instanceID().instanceID { (result, error) in
                if let error = error {
                    print("Error fetching remote instance ID: \(error)")
                } else if let result = result {
                    print("Remote instance ID token: \(result.token)")
                }
            }
    
            UIApplication.shared.registerForRemoteNotifications()
            updateFirestorePushTokenIfNeeded()
        }
    
        func updateFirestorePushTokenIfNeeded() {
            if let token = Messaging.messaging().fcmToken {
                //            let usersRef = Firestore.firestore().collection("users_table").document(userID)
                //            usersRef.setData(["fcmToken": token], merge: true)
                print("Remote instance ID token: \(token)")
            }
        }
    
        func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
            print("Firebase registration token: \(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.
        }
    
        func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
            print("Received data message: \(remoteMessage.appData)")
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
            print(response)
        }
    
        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
            if let messageID = userInfo[gcmMessageIDKey] {
                print("Message ID: \(messageID)")
            }
    
            print(userInfo)
        }
    
        func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            print("Unable to register for remote notifications: \(error.localizedDescription)")
        }
    
        func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let tokenParts = deviceToken.map { //data -> String in
                return String(format: "%02.2hhx", $0)
            }
    
            Messaging.messaging().apnsToken = deviceToken
            Messaging.messaging().setAPNSToken(deviceToken, type: .unknown)
            UserDefaults.standard.synchronize()
        }
    }
    

    这是使用以下所有链接设置的(我肯定还有一些其他链接我也忘了):

      null
    {
        "multicast_id": 2586780331808083728,
        "success": 1,
        "failure": 0,
        "canonical_ids": 0,
        "results": [
            {
                "message_id": "0:1578532253832479%2b1845e62b1845e6"
            }
        ]
    }
    

    云消息传递:

  • 共有1个答案

    赫连方伟
    2023-03-14

    我通过搬家来解决这个问题

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

    从PushNotificationManager到AppDelegate。希望这能帮助别人!

     类似资料:
    • 使用更新的Firebase cloud messaging和swizzling方法,当我的应用程序前景化时,我能够成功地在我的应用程序委托中的方法中接收有效负载。但是,我没有收到任何类型的有效负载,并且当我的应用程序处于后台时,不会被调用,尽管api响应消息已成功发送(见下文) 以下是我发送给FCM api的请求,以触发推送通知 有FCM的回复 这是我的appDelegate代码 我在我的应用程序

    • 我正在接收令牌,但当我从Firebase控制台发送通知时,我的设备上不会发生任何事情,无论应用是否处于后地。与此同时,我的Android应用程序收到通知。 我遵循了这个指南: https://firebase.google.com/docs/cloud-messaging/ios/client 为了确保这一点,我还在 https://github.com/firebase/quickstart-i

    • 我对FireBase云消息有一个问题,我从设备中获取令牌,并通过Google FireBase通知控制台发送通知测试。但是,通知从来没有被记录,也没有被推送到android虚拟设备。FCM的文档几乎与下面的代码完全相同,其他代码很少,您还需要做什么来获得使用FireBase的推送通知。我已经完成了所有的设置信息(build.gradle添加、安装google play服务等)如文档中所指定的,但仍

    • 我正在尝试使用Firebase Notification Composer向我的设备发送测试通知。我正在接收FCM令牌并将其打印到我的控制台,然后尝试向该令牌发送通知。 以下是我检查过的内容: 1) 我使用的是iOS 12.4.1 2) 我正在分配消息传递代理 3)我从委托方法接收FCM令牌 4) 我已经验证了通知是通过打印到控制台启用的,当提示我允许通知时,我单击了允许 5) 我已经验证了在Fi

    • 我在项目中使用Firebase身份验证。今天我决定将FCM集成到我的项目中。但是我无法从我的Firebase控制台收到任何通知。我还尝试重新下载. json文件,但没有成功。你们知道我的问题吗? Android清单.xml FirebaseMessageService.java FirebaseIDService.java 我认为这个问题不是由我的MainActiviy.java决定的,但以防万一

    • 我在Android中有一个应用程序,它接收来自firebase的通知,但当它在前台时,新的通知会取代以前的通知。我怎样才能全部展示出来?这是我的课。 公共类FirebaseNotifications扩展了FirebaseMessagingService{private static final String TAG=“MyFirebaseMsgService”; }