如何使用 Firebase 直接从 SwiftUI 应用程序发送推送通知,而不依赖 Firebase 网站?

问题描述 投票:0回答:1

虽然查找了许多执行此操作的方法,但似乎大多数人都是通过使用 Firebase 网站来完成此操作。我想做的是使用 Firebase 从 SwiftUI 应用程序本身发出推送通知。

我要问的是,我可以不依赖 Firebase 网站并在那里输入推送通知,而是通过 SwiftUI 应用程序可靠地完成此操作吗?

这是不起作用的示例:


import UIKit
import Firebase
import FirebaseMessaging
import Combine

class AppDelegate: UIResponder, UIApplicationDelegate, ObservableObject {

    var window: UIWindow?
    @Published var fcmToken: String?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { _, _ in })
        } else {
            let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        
        application.registerForRemoteNotifications()
        Messaging.messaging().delegate = self

        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications: \(error.localizedDescription)")
    }
}

@available(iOS 10, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        DispatchQueue.main.async {
            self.fcmToken = fcmToken
        }
        print("FCM registration token: \(fcmToken ?? "")")
    }
}


import SwiftUI


struct ContentView: View {
    @EnvironmentObject var appDelegate: AppDelegate
    
    var body: some View {
        Button(action: {
            self.sendPushNotification()
        }) {
            Text("Send Push Notification")
        }
    }
    
    func sendPushNotification() {
        guard let token = appDelegate.fcmToken else {
            print("FCM token not available")
            return
        }

        let urlString = "https://NOT_LETTING_SERVER_GET_SHOWN.json"
        guard let url = URL(string: urlString) else {
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        let body: [String: Any] = ["token": token]
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                return
            }
            
            if let data = data, let responseString = String(data: data, encoding: .utf8) {
                print("Response: \(responseString)")
            }
        }
        
        task.resume()
    }
}
`

import SwiftUI
import UIKit
import UserNotifications

@main
struct TestingPushNotesApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .environmentObject(appDelegate)
    }
}

当我不断尝试寻找方法时,它们似乎都不起作用,或者需要使用 Firebase 网站。

firebase swiftui firebase-cloud-messaging
1个回答
0
投票

无法通过 Firebase Cloud Messaging 直接安全地将消息从一台设备发送到另一台设备。您可以通过调用 FCM 的 API 来发送消息,但这需要一种只能在受信任的环境中使用的凭据 - 例如您的开发计算机、您控制的服务器或 Cloud Functions/Cloud Run 之类的东西。

© www.soinside.com 2019 - 2024. All rights reserved.