Ios 处理复杂firebase数据库查询的null返回

Ios 处理复杂firebase数据库查询的null返回,ios,swift,firebase-realtime-database,Ios,Swift,Firebase Realtime Database,我的应用程序内置了一个搜索功能,可以过滤firebase数据库中的用户 我能在一定程度上正确地做到这一点。问题是,每当我搜索不存在的用户时,应用程序就会崩溃,并出现错误:索引超出范围 这些是UICollectionViewCells,因此我处理在numberOfItemsInSection中返回的单元格,我认为我已经针对条件nil或zero进行了编码,但显然没有 这里是执行搜索的地方 func searchUsers(searchText: String) { let ref = Da

我的应用程序内置了一个搜索功能,可以过滤firebase数据库中的用户

我能在一定程度上正确地做到这一点。问题是,每当我搜索不存在的用户时,应用程序就会崩溃,并出现错误:
索引超出范围

这些是UICollectionViewCells,因此我处理在
numberOfItemsInSection
中返回的单元格,我认为我已经针对条件nil或zero进行了编码,但显然没有

这里是执行搜索的地方

func searchUsers(searchText: String) {

    let ref = Database.database().reference()
    ref.child("users").queryOrdered(byChild: "name").queryStarting(atValue: searchText).queryEnding(atValue: "\(searchText)\u{f8ff}")
        .observe(.childAdded, with: {(snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let user = User()
                user.setValuesForKeys(dictionary)

                self.users.append(user)
                print(snapshot)

                DispatchQueue.main.async(execute: {
                    self.collectionView?.reloadData()
                })
            }

                print(self.users.count)
        }, withCancel: nil)

}
有什么建议吗?

您不应该从
numberOfItems部分返回Int()
而是返回0

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   switch section {
   case 0:
      return users.count
   case 1:
     // handle based on section 1 datasource count
}

在仔细阅读文档之后,我能够推断出错误的来源。 以下是FireBase文档中的一行:

“如果指定位置不存在数据,FDataSnapshot将返回NSNull。”

因此,要绕过错误,通常您可以添加以下内容:

if snapshot.value == NSNULL {

    print("no users returned") 
} else {
//do something with data
然而,对于我正在执行的FireBase查询,观察结果是.childAdded事件

FireBase文档将这些查询称为复杂查询。在我的例子中,我使用的是只返回.child的
.queryStarting
.queryEnding
,它们添加了事件,因此在查询参数内检查值将不起作用,应用程序将崩溃

解决方案是在执行搜索之前检查查询是否返回null

如果使用数据返回collectionView或tableView单元格之类的内容,这一点尤为重要

最后,我所要做的就是在创建UICollectionViewCells之前,在查询返回值上添加一个引用观察值。最后看起来像这样

ref.observe(.value, with: { snap in
    if snap.value is NSNull {
        print("no users returned")
        self.users.removeAll()

        DispatchQueue.main.async(execute: {
        self.collectionView?.reloadData()
        })

    }
})

希望这对其他人有所帮助。

如果你的分区单元格数返回0,你的应用程序应该可以,我认为你永远不应该返回Int(),在任何情况下都不应该返回0你可能想要
返回用户?计数??0
@Paulw11仍在尝试将错误索引移出范围。还有另一个部分。我没有包括它,因为帖子越来越长。编辑答案后,如果没有数据,你应该返回0为什么这么复杂?
案例0:
的所有代码都可以是:
返回用户数。
。不需要
guard
。@rmaddy@suhit我仍然在
let user=users[indexPath.row]
@Stefan共享您的
用户
声明代码。