我正在尝试在SwiftUI 2.0中实现远程推送通知,但没有AppDelegate。我知道可以通过@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
提供一个,但我了解到这并不推荐。
我已经尝试通过Firebase Cloud Messaging触发通知,但我没有收到任何测试通知。我只弹出了允许通知的弹窗,然后什么也没发生。
我没有收到任何错误或其他提示..什么都没有发生。
我漏掉了什么吗?
测试结果:
Firebase 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.
}
}