我正在用SwiftUI和Firebase制作一个聊天应用程序,我想在用户收到新消息时显示通知. 我可以在Firebase中用云消息发送推送通知,但这些不是自动发送的.
现在,我想在用户收到消息时自动发送通信通知. 我在Swift和Firebase的后台找不到任何关于通信通知的教程.
import SwiftUI
import FirebaseCore
import FirebaseMessaging
@main
struct SimplePhoneApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
Main()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: { _, _ in }
)
application.registerForRemoteNotifications()
Messaging.messaging().delegate = self
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) async -> UIBackgroundFetchResult {
return .noData
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
let userInfo = notification.request.content.userInfo
print(userInfo)
return [[.alert, .sound]]
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let userInfo = response.notification.request.content.userInfo
print(userInfo)
}
func application(application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async -> UIBackgroundFetchResult {
// Messaging.messaging().apnsToken = deviceToken
print(userInfo)
return UIBackgroundFetchResult.newData
}
}
extension AppDelegate: MessagingDelegate {
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
)
}
}
以下是用于发送通信通知的工作代码:
func scheduleCustomNotification() {
let content = UNMutableNotificationContent()
content.title = "New Message"
content.body = "You have a new message from John Doe."
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) // Schedule notification to appear after 5 seconds
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: \(error)")
} else {
print("Custom notification scheduled successfully.")
}
}
}