swift firestore check if documents exists

≯℡__Kan透↙ 提交于 2020-05-15 04:46:24

问题


using swift and firestore I want to check the "Taken User Names" collection to see if a username has been taken and if it has alert the user it taken otherwise if it's still available I want to create the file.

The gist of what I want to do is outlined below, I can save the data no problem though its the checking to see if its document exists then taking action that I cannot figure out

func nextButtonPressed(){

     let db = Firestore.firestore()

    if usernameTextField.text != ""{
        guard let username = usernameTextField.text else { return }
        let docRef = db.collection("Taken User Names").document(username)
        // check if username exists{
        //if exists alert user "sorry user name taken
    } else {
        // if user name doesn't exist 
        db.collection("Taken User Names").document("trinidad")
                .setData(["Taken User Name" : (username)]) {
            (error: Error?) in
                if let error = error {
                   print("\(error.localizedDescription)")
                } else {
                   print("document was succesfully created and written")
                }
            }
    }
}

回答1:


func nextButtonPressed(){

   let db = Firestore.firestore()

   nextButton.isEnabled = false

    if usernameTextField.text != ""{

        guard let username = usernameTextField.text else { return }

        guard let uid = Auth.auth().currentUser?.uid else { return }

        let docRef = db.collection("Taken User Names").document(username)

        docRef.getDocument { (document, error) in
            if let document = document {


                if document.exists{
                    print("Document data: \(document.data())")

                    self.alertTheUser(title: "Username Taken", message: "please choose again")

                      self.nextButton.isEnabled = true

                } else {

                print("Document does not exist")



                }
            }
        }
    }
}



回答2:


In a cleaner way:

let docRef = db.collection("collection").document("doc")
docRef.getDocument { (document, error) in
       if document.exists {
         print("Document data: \(document.data())")
      } else {
         print("Document does not exist")
      }
}



回答3:


try the following:

let db = Firestore.firestore()
guard let username = userNameTextField.text else { return }

let docRef = db.collection("users").whereField("username", isEqualTo: username).limit(to: 1)
docRef.getDocuments { (querysnapshot, error) in
    if error != nil {
        print("Document Error: ", error!)
    } else {
        if let doc = querysnapshot?.documents, !doc.isEmpty {
            print("Document is present.")
        }
    }
}


来源:https://stackoverflow.com/questions/48224143/swift-firestore-check-if-documents-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!