当我从 Firebase 控制台发送通知时,它会发送到应用程序,但是当我点击通知横幅时,应调用函数
userNotificationCenter(_:didReceive:withCompletionHandler:)
并打印文本“didReceive method is called
”,但不会出现此类文本。我的代码有什么问题吗?
import SwiftUI
import FirebaseCore
import FirebaseAuth
import UserNotifications
import FirebaseMessaging
import FirebaseFirestore
let screen = UIScreen.main.bounds
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
Messaging.messaging().delegate = self
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("User notifications are allowed.")
} else {
print("User notifications are not allowed.")
} }
application.registerForRemoteNotifications()
application.applicationIconBadgeNumber = 0
return true
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("didReceive method is called")
let userInfo = response.notification.request.content.userInfo
print("userInfo is ", userInfo)
if let title = userInfo["title"] as? String,
let message = userInfo["message"] as? String {
// Create the PushNotificationView with the received title and message
let contentView = PushNotificationView(message: message, title: title)
print("__________________ FUNCTION userNotificationCenter_______________")
print("Message is: ", message)
pushMessage = message
print("Title is: ", title)
// Get the main window scene
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
// Access the relevant window from the window scene
if let window = windowScene.windows.first {
// Set the root view controller of the window to display the PushNotificationView
window.rootViewController = UIHostingController(rootView: contentView)
}
}
} else {
print("Title and message could not be retrieved")
}
completionHandler() // Call the completion handler when finished processing
}
}
extension AppDelegate: MessagingDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
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
)
if let fcmToken = fcmToken {
deviceToken = fcmToken}
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
}
@main
struct PirouetteApp: App {
// register app delegate
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
if let user = AuthService.shared.currentUser {
if user.uid == adminID || user.uid == admin2ID {
AdminOrderView()
} else {
let viewModel = MainTabBarViewModel(user: user)
MainTabBar(viewModel: viewModel)
}
} else {
AuthView()
}
}
.onChange(of: scenePhase) { newPhase in
if newPhase == .active {
// Clear badge count when app becomes active
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
}
}
我尝试自己做
我发现问题了。该错误与 Xcode 相关。我重新启动了我的笔记本电脑,didReceive 仍然没有被模拟器调用,但它开始在真实设备上工作。