How do I save data from cloud firestore to a variable in swift?
Solution 1:
That's because Firestore function getDocument
is an asynchronous
function and it returns immediately and after that it continues to execute the code inside it. If you want to return a particular value from here, you need to use completion Handler
. Your function may look like this.
func getDocument(path: String, field: String? = "nil", completion:@escaping(Any)->()) {
var returnVar : Any = "DEFAULT VAL"
var db: Firestore!
db = Firestore.firestore()
let docRef = db.document(path)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if(field != "nil"){
let property = document.get("phrase") ?? "nil"
returnVar = property
completion(returnVar)
}
else{
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
returnVar = dataDescription
completion(returnVar)
}
} else {
print("Document does not exist")
returnVar = -1
completion(returnVar)
}
}
}
Then call the function in viewDidLoad
or in any other function like this.
getDocument(path: path, field: field){(value) in
print(value)
}
You can checkout more about Completion Handlers
here