簡體   English   中英

檢查用戶名是否已經存在:Swift,Firebase

[英]Check if username already exist's : Swift, Firebase

我正在嘗試檢查用戶名是否存在。 當我調用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
        }

    })

通過操作安全規則,還可以將安全規則更改為所有人可讀(只讀)

{rules :{

   active_usernames : {

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

      }
    }
   }

PS: enteredUsername是您在其中輸入用戶名的textField。

建議:-將檢查代碼保留在textField的didChangeEditing事件內(以提供更好的用戶體驗。!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM