首页 > 解决方案 > 检查用户名是否存在于 Firebase

问题描述

我有一个这样的数据库

users/UID1/“用户名”(用户 1)

 /UID2/"Username" (of user 2)
 /UID3/"Username" (of user 3)
 /UID4/"Username" (of user 4)

等等..

我想检查用户名是否存在,但我无法使用所有现有的 UID 进入循环。现在我已经尝试过:

let databaseRef = Database.database().reference()        
            databaseRef.child("users").child("uid").child("Username").observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
                switch snapshot.value {
                case let value as Bool where value:
                    // value was a Bool and equal to true
                    print ("username found")
                default:
                    // value was either null, false or could not be cast
                    print ("username not found")
                }
            })

        }

我不知道该放什么而不是 child("uid") 循环到我的数据库中的每个 uid 并检查用户名是否存在

谢谢你的帮助 !

标签: swiftfirebasefirebase-realtime-database

解决方案


在安卓中

DataSnapshot 实例包含来自 Firebase 数据库位置的数据。每当您读取数据库数据时,您都会以 DataSnapshot 的形式接收数据。

DataSnapshot具有检查记录是否存在的exist() 方法。基于此文档https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot.html#exists()

像 :

reciverDatabase.getRef().addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                reciverDatabase.child(Constants.CONVERSATION_UNREAD_COUNT).setValue(dataSnapshot.getValue(Long.class) + 1);
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Crashlytics.logException(databaseError.toException());
                            sendMessageListener.onSendMessageFailure(databaseError.getMessage());
                        }
                    });

在 iOS 中:

你可以检查它:

对于目标 C: 存在

Desc :如果 DataSnapshot 包含非空值,则返回 YES。

您可以从此文档中阅读更多内容https://firebase.google.com/docs/reference/ios/firebasedatabase/api/reference/Classes/FIRDataSnapshot#/c:objc(cs)FIRDataSnapshot(im)exists

对于斯威夫特:

存在()

函数存在()->布尔

https://firebase.google.com/docs/reference/swift/firebasedatabase/api/reference/Classes/DataSnapshot#/c:objc(cs)FIRDataSnapshot(im)exists


推荐阅读