Firebase检查swift中的现有用户

时间:2016-04-27 21:16:26

标签: ios swift firebase

我有VC在哪里,我正在创建一个新用户并添加到firebase。用户不会在数据库中插入任何问题,但我无法检查是否已存在具有相同名称的用户。我尝试在firebase中使用各种查询语句,但没有得到任何乐趣。有谁知道如何修改我的代码来实现这一目标?这是: -

 @IBAction func submitUsername(sender: AnyObject) {

    if let user = usernameTxtField.text where user != "" {

       let username = DataService.ds.REF_USERS.childByAppendingPath("username")

       username.observeSingleEventOfType(.Value, withBlock: {  snap in

            if let usernameDoesNotExist = snap.value as? NSNull {
              let currentUser = DataService.ds.REF_USER_CURRENT.childByAppendingPath("username")
              self.usernameTxtField.text = user
              currentUser.setValue(user)
            }
       })

       dismissViewControllerAnimated(true, completion: nil)

    } else {
        showAlert("Username Needed", msg: "please choose a username")
    } 
}

和firebase数据结构

"users" : {
    "000591b6-ba88-4670-9cb7-edd79c273eab" : {
      "newuser" : "added to FB",
      "provider" : "password"
    },
    "05551c90-27fe-4969-b45d-279a72583857" : {
      "newuser" : "added to FB",
      "provider" : "password"
    },
    "0bbff1b0-681a-4fef-adc0-c4779a4b2100" : {
      "provider" : "password",
      "testing" : "emailtest",
      "username" : "richy446"
    },
    "12f35e7a-2430-49b3-a287-f7b1daf6a121" : {
      "newuser" : "added to FB",
      "provider" : "password",
      "username" : "richy445"
    },
    "15a45560-cc81-4c2d-bb59-b8ce6b125d68" : {
      "provider" : "password",
      "testing" : "emailtest",
      "username" : "richy445"
    },
    "1c135936-6dd0-4189-bcd7-e8036e9736f9" : {
      "newuser" : "added to FB",
      "provider" : "password"
    },
    "21591e29-f083-452c-b74f-cc567cecb183" : {
      "newuser" : "added to FB",
      "provider" : "password"
    },
    "8b385aa7-0e80-426b-a385-5b3317c894d0" : {
      "newuser" : "added to FB",
      "provider" : "password",
      "username" : "richy445"
    }
}

2 个答案:

答案 0 :(得分:4)

有许多方法可以检查重复数据。您拥有的Firebase结构似乎有些不一致,因此构建它可能更容易

"000591b6-ba88-4670-9cb7-edd79c273eab" : {
      "email" : "test@test.com",
      "password" : "password"
    },
"05551c90-27fe-4969-b45d-279a72583857" : {
      "email" : "test2@test.com",
      "password" : "password"
    },

1)让Firebase为您完成工作。

创建用户时,如果用户名(电子邮件)已存在,Firebase将返回错误。使用此方法可防止将随机数据写入您的Firebase,直到他们在Firebase中创建帐户为止。

myRootRef.createUser(email, password: pw, withValueCompletionBlock: { error, result in

    if error != nil {
        self.errMsgField.stringValue = "email/username in use, try again"

    } else {
        let uid = result["uid"] as! String //the uid of the new user
        print("user created as  \(uid)")
        self.storedDataInUserNode(email, password:pw)
        self.authUserWithAuthData( email, password: pw ) //auth the user
        // and proceed in starting up the app
    }
})

2)检查Firebase中的现有数据。

虽然第一种方法首先停止写入数据,但如果你想检查一般的重复数据,这里有一个模式:

let userName = the userName or email the user entered
let usersRef = Firebase(url:"https://test.firebaseio.com/users")
usersRef.queryOrderedByChild("email").queryEqualToValue("\(userName!)")
            .observeSingleEventOfType(.Value, withBlock: { snapshot in

        if ( snapshot.value is NSNull ) {
            print("not found)") //didnt find it, ok to proceed

        } else {
            print(snapshot.value) //found it, stop!
        }
 }

答案 1 :(得分:0)

在DataSnapshot上有一个名为.exists()的方法,你可以像这样调用它。 更新了Swift 4。

struct ModelUser {
    var id: String
    var name: String

    init(data: DataSnapshot) {
        // do init stuff
    }
}

func isUserRegistered(with id: String, completion: @escaping (_ exists: Bool, _ user: ModelUser?) -> ()) {
    DatabaseReference.users.child(id).observeSingleEvent(of: .value) { (snapshot) in
        if snapshot.exists() {
            // user is already in our database
            completion(true, ModelUser(data: snapshot))
        } else {
            // not in database
            completion(false, nil)
        }
    }
}