Swift 闭包和错误处理

标签 swift function firebase closures google-cloud-firestore

你好,我需要一些关于函数和/或该函数中的闭包的帮助。我希望我的函数检查 firestore 用户集合中的重复文档(用户名)。如果找到重复项,我想显示一条消息,如果没有找到重复项,则创建一个新用户。我有以下代码:

func checkIfUserExists(username: String, completion: @escaping (Bool) -> Void) {
    let docRef = db.collection("users").document(username)
    docRef.getDocument { (document, error) in
        if error != nil {
            print(error)
        } else {
            if let document = document {
                if document.exists {
                    completion(true)
                } else {
                    completion(false)
                }
            }
        }
    }
} 

然后我调用这个函数:

if let username = textField.text, username.count > 8 {              // Username needs to be more then 8 Char
    checkIfUserExists(username: username) { (doesExist) in
        if doesExist {
            print("user exists")
        } else {
            print("new User can be created")
        }
    }
} else {
    print("Username needs to be more then 8 char")
} 

它的工作原理,但我觉得这不是一个好的做法,我正在走弯路。这是正确的做法吗?

最佳答案

我认为您现在执行此操作的方式应该运行良好,但防止您在写入之前必须读取数据库的另一种选择是使用安全规则。例如,如果这是您的 users 集合的结构...

users: [
   username1: { // doc ID is the username
      userid: abcFirebaseUserId, // a field for the uid of the owner of the username
      //...etc
   }
]

...那么您可以使用以下规则:

match /users/{username} {
  allow create: if request.auth.uid != null;              
  allow update, delete: if resource.data.userId = request.auth.uid;
}

这允许任何经过身份验证的用户创建新用户名,但只有该用户名的所有者才能更新或删除它。如果您不允许用户更改他们的用户名,您甚至不必担心第二条规则。然后,在客户端中,您可以直接创建用户名,如下所示:

func createUsername(username: String, completion: @escaping (String?) -> Void) {
    guard let userId = Auth.auth().currentUser.uid else {
        completion("no current user")
        return
    }
    let docRef = db.collection("users").document(username)
    docRef.setData(data:[userId: userId]) { error in
        if let error = error {
            completion(error.debugDescription)
        } else {
            completion(nil)
        }
    }
} 

这会将新的用户名写入数据库,如果有的话,将错误传递给闭包。如果用户名已经存在,则会出现 insufficient permissions 错误。在检查用户是否存在时,您可以根据需要显示错误或提醒用户。

createUsername(username: username) { err in
    if let err = err {
        print("user exists")
    } else {
        print("new User has been created")
    }
}

虽然只是一个建议。我认为他们现在这样做也很好!

关于Swift 闭包和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955371/

相关文章:

swift - "static"对枚举或结构中的常量意味着什么

ios - 找到第一个共享父节点,它可以工作,但是可以做得更多 Swift-y 吗?

arrays - 在有序数组中快速查找元素

ios - 新的 Firebase 数据导致 TableView 单元格闪烁 (Firebase/iOS/Swift)

javascript - 如何在 firebase 中添加数据?

ios - 使用 Realm 或 UserDefaults 存储经过身份验证的用户数据?

javascript - 时间到了如何停止我的onclick功能?

c++ - 如何在类空间中为成员函数起别名?

Javascript:参数可以是任何东西吗?

android - Google Firebase 是否适用于 Android 版本 4.4.2(kitkat)?