Swift Firestore Search for users

爷,独闯天下 提交于 2020-01-03 03:23:07

问题


I've had already implemented a function to search for users using the FirebaseDatabase like that:

REF_USERS.queryOrdered(byChild: "username_lowercase").queryEnding(atValue: text+"\u{f8ff}").queryLimited(toFirst: 25).queryStarting(atValue: text).observeSingleEvent(of: .value, with:
            {
                (snapshot) in
                snapshot.children.forEach(
                    {
                        (s) in
                        let child = s as! DataSnapshot
                        if let dict = child.value as? [String: Any]
                        {
                            let user = UserInfo.createUser(dict: dict, key: child.key)
                            if user.id! != currentUserId
                            {
                                completion(user)
                            }
                        }
                })
        })

But now I've decided to switch from the Database to Firestore and since they've been bragging about their great querying I figured it shouldn't be too hard but for a few days now I've been trying to figure out how to search for users and can't seem to get it done.

Thats the code I have so far:

REF_USERS.order(by: "username_lowercased").limit(to: 25).order(by: text).getDocuments
        {
            (snapshot, error) in
            snapshot?.documents.forEach(
                {
                    (s) in
                    let child = s

                    let user = UserInfo.createUser(dict: child.data(), key: child.documentID)
                    if user.id! != currentUserId
                    {
                        completion(user)
                    }
            })
        }

But like i said nothing really works.

Any suggestions? Id really appreciate it c:

-Marie


回答1:


First of all start by handling errors. Errors in Firestore are very descriptive and they will guide you what needs to be done in order for your query to work.

guard let snapshot = snapshot else {
    // Make your completion handler work with errors as well so you can read / display them
    // completion(nil, error)
    // For now just print the error
    print(error!)
    return
}

Also when you want to call a success completion handler when a condition is met, I suggest you just use a for loop and break when needed:

for document in snapshot.documents {
    if user.id! != currentUserId {
        completion(user)
        break
    }
}

I hope this helps.



来源:https://stackoverflow.com/questions/53562247/swift-firestore-search-for-users

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