我正在用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.")
        }
    }
}

推荐答案

?()触发本地通知,无论如何它都与FireBase无关.

您需要判断:

  • 如果您将.p12或p8文件添加到Firebase控制台.
  • 您可以从Firebase控制台发送远程通知以查看您接收到的内容(Firebase处理您的通知的构建).
  • 判断您的项目背景模式(已激活远程通知).

或许它能帮上忙: iOS Handle notifications and payload when app is in Background

https://www.kodeco.com/20201639-firebase-cloud-messaging-for-ios-push-notifications

Ios相关问答推荐

SwiftUI中的视频时间轴

在SwiftUI中动态隐藏列表的空部分

SWIFT用户界面检测手势的开始和结束

当S没有身体时该如何处理

为什么iOS委派在KMM中不能正常工作?

CIKernel的Metal Shader裁剪问题

多协议和类继承混乱,Swift

Swift Vision库识别文本后如何将其赋值给 struct 体实例属性以供显示?

Apple Metal iOS 为什么 GLKMatrix4MakeLookAt 来回摇摆

具有线性渐变的 SVG textPath 在 Safari 中损坏

弹出视图后使所有背景 UI 模糊

有没有办法访问自动生成的 Codable 一致性的编码键?

为什么我的应用在 Testflight 中没有下载 dSYM 按钮?

iPhone 6 和 6 Plus 媒体查询

如何找出坐标之间的距离?

关闭所有打开的视图控制器的单个函数

标题为 UIImage 的导航栏

aps-environment 始终在发展

如何使用完成按钮制作 UIPickerView?

UITextView 内容插图