[英]How do I connect Firestore to my firebase app
互聯網上到處都是關於這方面的教程使用舊版本的swift,它使用場景委托和應用程序委托文件
如何將簡單的 Firestore 連接到我的 Firebase 應用
這是我的代碼不起作用:
Firestoremanager.swift
import FirebaseFirestore
import FirebaseFirestoreSwift
import Combine
import Firebase
class FirestoreManager: ObservableObject {
@Published var restaurant: String = ""
func fetchRecipie() {
let db = Firestore.firestore()
let docRef = db.collection("Recipies").document("recipie")
docRef.getDocument { (document, error) in
guard error == nil else {
print("error", error ?? "")
return
}
if let document = document, document.exists {
let data = document.data()
if let data = data {
print("data", data)
self.restaurant = data["name"] as? String ?? ""
}
}
}
}
func FetchAllRecipies() {
let db = Firestore.firestore()
db.collection("Recipies").getDocuments() { (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID): \(document.data())")
}
}
}
}
init() {
FetchAllRecipies()
}
}
RecipieApp.swift
import SwiftUI
import Firebase
@main
struct RecipyApp: App{
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var firestoreManager = FirestoreManager()//I try to connect here
var body: some Scene{
let viewModel = AppViewModel()
WindowGroup{
ContentView()
.environmentObject(viewModel)
.environmentObject(firestoreManager)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate{
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
然后當我在主視圖文件中運行Text("My restaurant: \\(firestoreManager.recipie)")
我收到一個錯誤
“實例方法‘appendInterpolation’要求‘綁定’符合‘_FormatSpecifiable’”
我怎樣才能克服這個錯誤?
在你的@main
結構中輸入:
init() {
FirebaseApp.configure()
}
這就是你需要做的一切
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.