要在SwiftUI中使用Firestore制作动态视图,你需要遵循以下步骤:
npm install firebase npm install swiftui ``` ```bash pip install google-cloud-firestore
Info.plist
文件,添加以下内容:<key>FirebaseAppID</key> <string>YOUR_FIREBASE_APP_ID</string> <key>GoogleService-Info.plist</key> <string>YOUR_FIREBASE_PROJECT_ID</string>
AppDelegate.swift
文件中,导入Firebase模块并初始化Firebase:import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() return true } }
struct User: Identifiable { @DocumentID var id: String? let name: String let age: Int }
import SwiftUI import Firebase import FirebaseFirestore struct FirestoreView: View { @StateObject private var firestoreVM = FirestoreViewModel() var body: some View { VStack { List(firestoreVM.users) { user in VStack(alignment: .leading) { Text(user.name) .font(.headline) Text("\(user.age) years old") .font(.subheadline) } } } .padding() .onAppear { firestoreVM.loadData() } } }
import SwiftUI import Firebase import FirebaseFirestore class FirestoreViewModel: ObservableObject { @Published var users: [User] = [] private var db: FirestoreDatabase init() { db = Firestore.database() } func loadData() { let usersRef = db.collection("users") usersRef.addSnapshotListener { snapshot, error in if let error = error { print("Error fetching data from Firestore: \(error.localizedDescription)") return } guard let documents = snapshot?.documents else { return } let users = documents.compactMap { document in do { let data = try document.data(as: User.self) return data } catch { print("Error decoding user data: \(error.localizedDescription)") return nil } } DispatchQueue.main.async { self.users = users } } } }
FirestoreView
添加到视图层次结构中:import SwiftUI struct ContentView: View { var body: some View { FirestoreView() } }
现在,当你运行你的SwiftUI应用程序时,它将从Firestore数据库加载用户数据并在屏幕上显示。请确保你的Firestore数据库中有一个名为users
的集合,并且其中包含一些用户文档。
领取专属 10元无门槛券
手把手带您无忧上云