gpt4 book ai didi

ios - Firebase Cloud Messaging 通知未显示在 iOS 设备上(前台和后台)

转载 作者:行者123 更新时间:2023-12-01 15:44:31 24 4
gpt4 key购买 nike

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

开发环境:

  • Xcode 11.3

  • 运行 iOS 13.3 的 iPhone X

  • swift 5.2

Pod 版本:

  • Firebase 6.14.0
  • FirebaseMessaging 4.1.10
  • FirebaseInstanceID 4.2.8

问题:

在遇到问题之前,我已将我的应用程序设置为能够在应用程序处于后台和前台时接收通知。我对自己提交了代码感到非常满意。在此之后,我无法在前台或后台接收通知。无论使用通知是从 Cloud Messaging 仪表板还是 POSTMAN 发送的,我都会收到成功的响应,但通知从未出现。

起初我以为我可能已经达到了通知配额,但现在已经是 2 天了。

为了排除故障我已经尝试过:

  1. 卸载并重新安装应用(刷新设备 token )
  2. UIApplication.shared.registerForRemoteNotifications() 移动到 FirebaseApp.configure() 之前
  3. 下载新的 GoogleService-Info.plist 并替换现有的
  4. 检查包 ID 等是否全部匹配
  5. 将 firebase pod 更新到最新版本(如果有帮助,FirebaseMessaging 是 4.1.9)
  6. 设置 Messaging.messaging().shouldEstablishDirectChannel = true
  7. 删除并重新添加所需的功能
  8. FirebaseAppDelegateProxyEnabled 设置为 YES 和 NO
  9. 设置shouldEstablishDirectChannel = true
  10. 设置useMessagingDelegateForDirectChannel = true
  11. 将一些逻辑从 didFinishLaunchingWithOptions() 移到了 applicationDidBecomeActive()

代码:

注意:这是最初为我工作的未更改代码。

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

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

响应信息:

postman :

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

云消息:

FCM Console

最佳答案

我能够通过移动来解决问题

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

从 PushNotificationManager 到 AppDelegate。希望这对其他人有帮助!

关于ios - Firebase Cloud Messaging 通知未显示在 iOS 设备上(前台和后台),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59656069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com