【发布时间】:2021-01-03 03:55:47
【问题描述】:
我有多个视图,并希望在点击按钮时在每个不同的视图中更改 Firestore 数据库。
在firstView 中,我已将数据设置为 Firestore,并希望在点击按钮时在第二个视图中更新它们。
我注意到我不能在每个不同的视图中调用 Firestore。
作为初学者,如何在不同的视图中实现数据更新?
import SwiftUI
import Firebase
struct firstView: View {
var body: some View {
VStack {
Text("Greetings!")
Button(action: {
self.writeDatabase()
}) {
Text("Next")
}
}
}
func writeDatabase() {
let firestoreDatabase = Firestore.firestore()
let firestorePost = [
"PostedBy": Auth.auth().currentUser!.email!,
"date": FieldValue.serverTimestamp(),
"CityName": "",
"DistrictName": ""] as [String : Any]
firestoreDatabase
.collection("Posts")
.document("Dc")
.setData(firestorePost, merge: true) { error in
if error != nil {
print("error")
}
}
}
}
我的第二种看法如下:
import SwiftUI
import Firebase
struct secondView: View {
var body: some View {
NavigationView {
VStack {
Text("Tap to update...")
NavigationLink(destination: good()) {
Text("Next")
}
.onAppear {
self.update()
}
}
}
}
func update() {
let firestoreDatabase = Firestore.firestore()
firestoreDatabase
.collection("Posts")
.document("Dc")
.updateData(
[
"CityName" : "İstanbul",
"DistrictName": "Beşiktaş"
]
) { (error) in
if error != nil{
print("Error")
}
else {
print("succesfully updated")
}
}
}
}
}
【问题讨论】:
标签: swift firebase google-cloud-firestore swiftui