ios - 如何检查 childByAutoID() 是否已存在于 Firebase 实时数据库中?

标签 ios swift xcode firebase firebase-realtime-database

我正在使用 Facebook 和 Google 登录协议(protocol)让我的用户登录。我可以通过以下方式存储这些用户:

 let firebaseID = Auth.auth().currentUser?.uid
    let userID = user.userID
    let fullName = user.profile.name
    let email = user.profile.email
    let provider = "Google"
    guard let authentication = user.authentication else {return}
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
    Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
            if let error = error {
                print("Failed to create Firebase User with Google: ", error)
                return        
            }
            print("Successful creation of Firebase User with Google")
            let databaseRef = Database.database().reference()
            let key = databaseRef.child("node").childByAutoId().key
            let userInfo = ["UID": userID,
                            "Full Name": fullName,
                            "Email": email,
                            "Provider": provider]
            let childUpdates = ["/Users/\(key)/": userInfo]           
    databaseRef.updateChildValues(childUpdates)

每次我登录时,即使使用相同的凭据,也会使用相同的登录用户创建一个新用户。如果特定用户之前已登录,我如何防止创建新实例。

enter image description here

最佳答案

你应该使用:

let childUpdates = ["/Users/\(userID)/": userInfo] 

这样可选的就不会出现,你应该这样写:

let key = databaseRef.child("node").childByAutoId().key ?? ""    

如果你想捕获/防止 nil,或者打开它

let key = databaseRef.child("node").childByAutoId().key!

但是,由于当同一个用户输入新信息时用户 ID 不会改变,并且每次用户输入时您都在使用自动键,因此每次都会创建一个新的 child 。

关于ios - 如何检查 childByAutoID() 是否已存在于 Firebase 实时数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53329082/

相关文章:

javascript - 登录 react native 后如何更改导航器初始路线

ios - SpriteKit - 生成随机节点

ios - 点击 Collection View 单元格以向 map 添加注释

ios - 使用 Swift 从 Firebase 读取单个值

ios - 如何在 IOS 的 wkwebview 中隐藏 html 元素?

ios - 无法将已解析的 JSON 列表显示到 TableView 中

Swift 3 - 如何从 FireBase 存储下载配置文件图像

ios - Swift 无法从 parse.com 检索图像

ios - react-native run-ios 不工作

ios - Xcode 无法调试 View 框架