I have multiple views and want to make a change in Firestore database in every different views when button is tapped.
In firstView, I have set my data to Firestore and want to update them in the second view when button is tapped.
I noticed that I can not call Firestore in every different view.
As I'm a beginner, how can I implement data updates in different views?
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")
}
}
}
}
My second view is as follows:
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")
}
}
}
}
}