Swift & Firebase | Checking if a user exists with a username

落爺英雄遲暮 提交于 2019-11-26 23:05:24

问题


I am trying to allow users to start games with and follow other users by searching their username. I need to be able to make sure that a user with that username exists. I was using the following code but although the if is called the else does not get called when it should.

let checkWaitingRef = Firebase(url:"https://test.firebaseio.com/users")
checkWaitingRef.queryOrderedByChild("username").queryEqualToValue("\(username!)")
            .observeEventType(.ChildAdded, withBlock: { snapshot in

    if snapshot.value.valueForKey("username")! as! String == username! {

    } else {

    }

JSON data tree

{
    "097ca4a4-563f-4867ghj0-6209288bd7f02" : {
        "email" : "test1@tes1.com",
        "uid" : "097ca4a4-563f-4867ghj0-6209288bd7f02",
        "username" : "test1",
        "waiting" : "0"
    },
    "55a8f979-ad0d-438u989u69-aa4a-45adb16175e7" : {
        "email" : "test2@test2.com",
        "uid" : "55a8f979-ad0d-438u989u69-aa4a-45adb16175e7",
        "username" : "test2",
        "waiting" : "0"
    }
}

回答1:


Easy fix:

Don't use .childAdded as the block will not execute when the query doesn't find anything.

Instead use .Value and check for NSNull

    let checkWaitingRef = Firebase(url:"https://test.firebaseio.com/users")
    checkWaitingRef.queryOrderedByChild("username").queryEqualToValue("\(username!)")
                .observeEventType(.Value, withBlock: { snapshot in

            if ( snapshot.value is NSNull ) {
                print("not found)")

            } else {
                print(snapshot.value)
            }
     })


来源:https://stackoverflow.com/questions/36442114/swift-firebase-checking-if-a-user-exists-with-a-username

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