gpt4 book ai didi

ios - 没有 AppDelegate 的 SwiftUI 远程推送通知(Firebase 云消息传递)

转载 作者:行者123 更新时间:2023-12-04 11:56:55 26 4
gpt4 key购买 nike

我正在尝试在 SwiftUI 2.0 中实现远程推送通知,但没有 AppDelegate。我知道我可以通过 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 提供一个但我了解到不推荐这样做。
我尝试通过 Firebase Cloud Messaging 触发通知,但没有收到任何测试通知。我刚刚弹出以允许通知,仅此而已。
我没有收到任何错误或其他任何东西.. 什么也没发生。
我错过了什么吗?
考试:
enter image description hereFirebase registration token: Optional("fwRsIKd7aUZeoLmmW5b4Zo:APA91bHrVvArS-mLZMEkdtzTxhRUuMWVgHNKXdLethAvR3Fa3h_RmAcdOz_jJzp1kDsEEtcvbnAFUn9eh9-cUSCTy9jBibbFoR2xngWdzWCvci1_iLQJtHtCjxk-C02CkVUDl7FX8esp")这是我的代码:

import SwiftUI
import Firebase
import OSLog

@main
struct Le_fretApp: App {
@StateObject var sessionStore = SessionStore()
@StateObject var locationManagerService = LocationManagerService()
@StateObject var userViewModel = UserViewModel()

var notificationsService = NotificationsService()



init() {
UIApplication.shared.delegate = NotificationsService.Shared
FirebaseConfiguration.shared.setLoggerLevel(.min)

notificationsService.register()

FirebaseApp.configure()

notificationsService.setDelegate()
}

var body: some Scene {
WindowGroup {
TabViewContainerView()
.environmentObject(sessionStore)
.environmentObject(userViewModel)
.environmentObject(locationManagerService)
.onAppear {
sessionStore.listen()
userViewModel.listen()
}
}
}
}
服务:
import Foundation
import UserNotifications
import OSLog
import UIKit

import Firebase


class NotificationsService: NSObject, UNUserNotificationCenterDelegate {
static let Shared = NotificationsService()
let gcmMessageIDKey = "gcmMessageIDKey"

func register() {
// 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 })

DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}


// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

// Change this to your preferred presentation option
completionHandler([[.alert, .sound]])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print full message.
print(userInfo)

completionHandler()
}
}

extension NotificationsService: UIApplicationDelegate {
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)

// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}

// Print full message.
print(userInfo)

completionHandler(UIBackgroundFetchResult.newData)
}
}

extension NotificationsService: MessagingDelegate {
func setDelegate() {
Messaging.messaging().delegate = self
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: 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.
}
}

最佳答案

Le_fretApp.initUIApplication.shared 合作还为时过早,因为它还没有在那里初始化。
尝试在场景创建时(或在其他您认为需要且应用程序已初始化的地方)执行此操作。

@main
struct Le_fretApp: App {
// ... other code here

func createScene() -> some Scene {
if nil == UIApplication.shared.delegate {
UIApplication.shared.delegate = NotificationsService.Shared // << !!
}

return WindowGroup {
// ... your scene content here
}
}

var body: some Scene {
createScene()
}
并且,顺便说一句,我认为这个属性也应该引用相同的服务实例,即共享
var notificationsService = NotificationsService.Shared    // !!

关于ios - 没有 AppDelegate 的 SwiftUI 远程推送通知(Firebase 云消息传递),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65444380/

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