使用swift和firestore我想查看"采取的用户名"收集以查看是否已使用用户名,以及是否已提醒用户,否则如果它仍然可用我想创建该文件。
我想要做的事情的要点概述如下,我可以保存数据没有问题,虽然检查它的文件是否存在然后采取我无法弄清楚的行动
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")
}
}
}
}
答案 0 :(得分:6)
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")
}
}
}
}
}
答案 1 :(得分:2)
尝试以下操作:
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.")
}
}
}
答案 2 :(得分:2)
以一种更清洁的方式:
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")
}
}