Swift Firestore搜索用户 [英] Swift Firestore Search for users

查看:49
本文介绍了Swift Firestore搜索用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了使用 FirebaseDatabase 来搜索用户的功能,如下所示:

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

但是现在我决定从 Database 切换到 Firestore ,由于他们一直在吹嘘自己的出色查询,所以我认为这样做不应该太难但是几天以来,我一直在试图找出如何搜索用户的方法,但似乎并没有完成它.

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.

有什么建议吗?我真的很感激c:

Any suggestions? Id really appreciate it c:

-玛丽

推荐答案

首先从处理错误开始.Firestore中的错误具有很强的描述性,它们将指导您进行哪些操作才能使查询正常工作.

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
}

另外,当您希望在满足条件时调用成功完成处理程序时,我建议您仅使用for循环并在需要时中断:

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

我希望这会有所帮助.

这篇关于Swift Firestore搜索用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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