斯威夫特&火力基地 |检查用户是否存在用户名 [英] Swift & Firebase | Checking if a user exists with a username

查看:21
本文介绍了斯威夫特&火力基地 |检查用户是否存在用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图允许用户通过搜索用户名来开始游戏并关注其他用户.我需要能够确保存在具有该用户名的用户.我正在使用以下代码,但尽管 if 被称为 else 并没有在它应该调用的时候被调用.

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 数据树

{
    "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"
    }
}

推荐答案

简单修复:

不要使用 .childAdded,因为当查询没有找到任何东西时,块将不会执行.

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

改为使用 .Value 并检查 NSNull

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)
            }
     })

这篇关于斯威夫特&火力基地 |检查用户是否存在用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆