当应用程序变量更改时触发Firestore查询

问题描述

这可能是一个非常基本的问题,但是我是SwiftUI和Firestore的新手,所以我有点挣扎。我正在构建一个显示我附近俱乐部位置的应用程序。我在Firestore中拥有我的Clubs集合,每个文档都有一个geoPoint和geoHash。启动应用程序时,我正在使用位置管理器向我提供当前位置,然后将其转换为searchGeoHash和searchGeoBox,然后按以下方式查询Firestore:

@Published var searchGeoHash: String = Geohash.encode(latitude: locationManager.location?.latitude ?? 0,longitude: locationManager.location?.longitude ?? 0,5)
@Published var searchGeoBox: [String] = (Geohash.neighbors(String(searchGeoHash.prefix(4)))?.sorted())!

self.db.collection(K.Firebase.clubCollection)
    .whereField("clubActive",isEqualTo: true)
    .whereField("clubGeoHash",isGreaterThanorEqualTo: searchGeoBox[0])
    .whereField("clubGeoHash",isLessthanorEqualTo: searchGeoBox[7])
    .addSnapshotListener { querySnapshot,error in
        guard let documents = querySnapshot?.documents else {
            print("Error fetching Club documents: \(error!)")
            return
        }
        self.clubList.removeAll(keepingCapacity: false)
        print("Club Count - from Firestore: ",documents.count)

        for doc in documents {
            let mappedDoc = Club(dictionary: doc.data())
            self.clubList.append(mappedDoc!)
        }
        self.clubListCount = self.clubList.count
        print("Club Count - from Field: ",self.clubList.count)
    }

这行得通,因为它向我显示了范围内的球杆。

我还有另一个功能,该功能允许用户更改其位置以搜索其他位置的俱乐部。例如,我目前在波士顿,但我想搜索纽约的俱乐部。此功能更新searchGeoHash和searchGeoBox

此问题是由于更改了searchGeoHash和searchGeoBox之后,如何自动触发此查询以进行更新。

我是否必须重新运行查询,还是以其他方式使用安装程序searchGeoHash和searchGeoBox?我应该使用观察对象还是合并对象?

解决方法

由于存在以下问题,如何自动触发此查询以进行更新 更改了searchGeoHash和searchGeoBox。

您可以使用didSet

@Published var searchGeoHash: String = Geohash.encode(...) {
    didSet {
        // trigger your query...
    }
}