ios - 检查用户名是否已经存在的 : Swift, Firebase

标签 ios swift firebase firebase-realtime-database

我正在尝试检查用户名是否存在。当我调用 queryOrderedBychild 时,快照值始终可用,但它会打印出我的整个数据库,而不仅仅是我请求 queryOrderby 的数据。当我调用 queryEqualToValue 时,它总是返回 null。我尝试了很多方法来解决这个问题。

这是我的代码:

DataService.instance.UsersRef.queryOrdered(byChild:"Nickname").queryEqual(toValue: "kai1004pro").observe(.value, with: { (snapshot) in

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




    })

这是我的 json 树:

Optional({
g50X0FvEsSO4L457v7NzS3dAABl1 =     {
    "User Profile" =         {
        Birthday = "Sep 20, 1992";
        Gender = Female;
        Nickname = kai1004pro;
        UserUID = g50X0FvEsSO4L457v7NzS3dAABl1;
        emailAddress = "poqksbs@gmail.con";
        isFollow = 0;
        isFriend = 0;
    };
};
})

这是安全规则:

"rules": {
".read": true,
".write": "auth != null",
"Users": {
  ".read": true,
  ".write": "auth != null",
  ".indexOn": ["Nickname", "User Profile"]
    }
  }
}

最佳答案

修改您的 JSON 树以包含一个单独的节点 active_usernames,每当您创建新用户时添加每个用户的用户名,每当您的用户修改其用户名时修改.. .

myApp:{
  users:{
    uid1:{....},
    uid2:{....},
    uid3:{....},
    uid4:{....},
  }
active_usernames :{
    uid1username : "true",
    uid2username : "true",
    uid3username : "true",
    uid4username : "true"
    }
}

检查您的用户名是否已存在:-

//Checking username existence
FIRDatabase.database().reference().child("active_usernames").child(self.enteredUsername.text!).observeSingleEvent(of: .value, with: {(usernameSnap) in

        if usernameSnap.exists(){
        //This username already exists

        }else{

        //Yippee!.. This can be my username
        }

    })

同时通过操纵安全规则,将您的安全规则更改为对所有人(ONLY READABLE)可读。

{rules :{

   active_usernames : {

      ".read" : "true",
      ".write" : "auth != null"

      }
    }
   }

PS:- enteredUsername 是您输入用户名的文本字段。

建议:- 将检查代码保留在 textField 的 didChangeEditing 事件中(为了更好的用户体验。!)

关于ios - 检查用户名是否已经存在的 : Swift, Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39607961/

相关文章:

swift - 将 CALayer 渲染为任意大小的图像

即使通过 npm 安装并重新登录后,flutterfire configure 也无法正常工作

ios - 当 supportedInterfaceOrientations 发生变化时如何通知系统?

ios - 如何在 uitableview for IOS 中使用 Reusable Cells

iOS 8 和 segues 抛出意外异常

android - 无法使用 Firebase ICON android 更改我的通知

android - 处理 Android 系统托盘中已关闭的 Firebase 通知

ios - View 中CircleView的Circle位置错误

ios - 为什么我的 Vapor 查询总是失败?

ios - 如何使用 Swift 将图像上传到 iOS 中的服务器?