Reputation: 7
I want to write a function where it's input the username the user enter and it compared with username feild in firestore if it's exists the function must return false and if not must return true
Here is my code.. It always return true when I call it !
func checkUser(username: String)-> Bool{
var test = true
FirebaseReference(.user).getDocuments { (snap, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
for i in snap!.documents{
if username == i.get("username") as! String {
test = false
print("name already taken")
}
}
}
return test
}
Upvotes: 0
Views: 939
Reputation: 626
Use Async Await
func checkUser(userId: String) async throws -> Bool {
let querySnapshot = try await db.collection(path)
.whereField("userId", isEqualTo: userId).getDocuments()
if querySnapshot.isEmpty {
return false
} else {
for document in (querySnapshot.documents) {
if document.data()["userId"] != nil {
return true
}
}
}
Initialize with Task
Task.init {
if try await self.userRepository.checkUser(userId: user.uid) == false {
self.userRepository.addUser(FBUser(id: user.uid,
name: "Anonymous user",
email: "No email on file",
createdTime: Timestamp(),
userId: user.uid))
}
}
Upvotes: 0
Reputation: 2487
You can use a boolean variable to check if you have found a matching name, and you can set it to true if you find a match.
You can use the following code:
func checkUsername(username: String, completion: @escaping (Bool) -> Void) {
// Get your Firebase collection
let collectionRef = db.collection("users")
// Get all the documents where the field username is equal to the String you pass, loop over all the documents.
collectionRef.whereField("username", isEqualTo: username).getDocuments { (snapshot, err) in
if let err = err {
print("Error getting document: \(err)")
} else if (snapshot?.isEmpty)! {
completion(false)
} else {
for document in (snapshot?.documents)! {
if document.data()["username"] != nil {
completion(true)
}
}
}
}
}
Upvotes: 1