I have been recently learning to use Firebase in iOS development, and have been consistently running into this error. I currently have two documents in my database's "users" collection, which represent two users. I am using this function in order to retrieve all data from my "users" collection:
func retrieveAllInfo() {
db.collection("users").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
}
else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
}
}
However, when I try to implement this function as the action of a SwiftUI button, I get this error:
Cannot convert value of type '()' to expected argument type '() -> Void'
I don't really understand what is going on. I was able to use functions I wrote to write users to the database as actions for SwiftUI buttons, but this specifically is throwing an error. It doesn't seem to me like it has any return type (or at least something different from the functions I wrote to write to the database). Here is an example of one of the functions I used to write to the database:
func addAlanTurning() { //Adding to a new document + collection
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": "Alan",
"Middle": "Mathison",
"last" : "Turing",
"born" : 1912
]) { err in
if let err = err {
print("error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
}
Any help would be greatly appreciated. Thank you in advance.
Edit:
I managed to add the action to the button, however, the problem still persists in a different form. When I wrote a new function to add a user with parameters for each of the user's attributes, the button threw the same error when I tried to add the function to it with the parameters filled. Here is the new function:
func addUser(first: String, middle: String, last: String, age: Int) { //Adding to a new document + collection
var ref: DocumentReference? = nil
ref = db.collection("users").addDocument(data: [
"first": first,
"Middle": middle,
"last" : last,
"age" : age
]) { err in
if let err = err {
print("error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
}
Here is how it is implemented in the button where it throws the error:
struct ContentView: View {
let db = Firestore.firestore()
@State private var first: String = ""
@State private var middle: String = ""
@State private var last: String = ""
@State private var age: Int = 25
var body: some View {
VStack {
TextField("First Name:", text: $first)
TextField("Middle Name:", text: $middle)
TextField("Last Name:", text: $last)
Stepper(value: $age, in: 13...99) {
Text("Age: \(age)")
}
Button(action: addUser(first: first, middle: middle, last: last, age: age)) {
Text("Add User")
}
}
.padding()
}
Thank you in advance.