I want to read data from Firebase and return the output as a Dict to my ViewController.
I did not manage to get the data returned in a valid way.
This is how I read the data:
func getCollectionData() -> Dictionary<String, String> {
var returnValue: String = ""
db.collection(user).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: (err)")
returnValue = ""
} else {
for document in querySnapshot!.documents {
let returnValue = document.data() as? Dictionary<String, String>
print (returnValue)
}
}
}
return returnValue
}
Error:
Cannot convert return expression of type 'String' to return type 'Dictionary<String, String>'
Why is returnValue
String again?
I fiddled around a lot, but never found a solution, to return the data in a good way.
The output of print(returnValue) shows it’s a dictionary
Optional(["url": "https://firebasestorage.googleapis.com:443/v0/b/.....9c5e73f", "email": "[email protected]"])
In my ViewController I want to use the data to fill a tableView:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = Array(myReturnedDict.values)[indexPath.row]
return cell
}
EDIT:
I still get an empty Dictionary back as a returned value:
func getCollectionData() -> Dictionary<String, String> {
var returnValue = [String: String]()
db.collection(user).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: (err)")
returnValue = ["No":"data"]
} else {
for document in querySnapshot!.documents {
print (user)
returnValue = (document.data() as? Dictionary<String, String>)!
//print (returnValue)
}
}
}
return returnValue
}
Can somebody help me?
2
Answers
You created
var returnValue: String = ""
and use it default value "".To avoid it you need to change
returnValue
to type Dictionary<String, String> and setreturnValue
not likebut