Swift iOS Firebase - Как объединить queryOrdered (byChild) и GeoFire наблюдать (.keyEntered), чтобы получить снимок и результат местоположения одновременно? - PullRequest
0 голосов
/ 27 октября 2018

Используя UISearchController, если я хочу выполнить поиск любимой книги пользователя по имени Гарри Поттер, я бы сделал следующее, чтобы получить ее снимок:

func updateSearchResults(for searchController: UISearchController) {

    // the searchText the user entered is Harry Potter
    guard let searchText = searchController.searchBar.text?.lowercased() else { return }

    let favoriteBooksRef = Database.database().reference().child("searchFavoriteBooks").queryOrdered(byChild: "titleLowercased").queryStarting(atValue: searchText).queryEnding(atValue: searchText+"\u{f8ff}")

    favoriteBooksRef.observeSingleEvent(of: .value, with: { (snapshot) in
        ...
    })
}

Если бы я хотел искать пользователей в определенном месте, я бы выполнил следующее с GeoFire:

let geofireRef = Database.database().reference().child("users_locations")
let geoFire = GeoFire(firebaseRef: geofireRef)
let center = CLLocation(latitude: myLat, longitude: myLon)

let circleQuery = geoFire.query(at: center, withRadius: 5)

var queryHandler = circleQuery.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
       ...
})

Как я могу использовать UISearchController для объединения обоих запросов, чтобы я мог получить снимок всех пользователей с любимым названием книги Гарри Поттера в пределах 5 км от моего местоположения?

Согласно этой ссылке человек говорит просто добавить третий параметр в качестве снимка в GFQueryResultBlock, но он не объясняет, как этот снимок достигает другого узла для извлечения данных.

Моя база данных (в ней отображается 1 пользователь, но поблизости могут находиться 20 пользователей, которые появятся в результатах поиска):

-root
   |
   @--users
   |    |
   |    @---uid789
   |          |
   |          |--username: "avidBookReader"
   |          |--lat: 34.111
   |          |--lon: -34.222
   |          @---postId001
   |                  |
   |                  |--title: "Harry Potter"
   |
   @--users_location
   |    |
   |    @---uid789
   |          |
   |          |--g: xyz234
   |          @--l:      
   |              |--0: 34.111
   |              |--1: -34.222
   |
   @--searchFavoriteBooks
        |
        @---postId001
               |
               |--uid: "uid789"
               |--titleLowercased: "harry potter"
               |--lat: 34.111
               |--lon: -34.222

То, что я пробовал до сих пор. Я сначала проверил всех пользователей, ближайших к устройству, а затем поместил их в массив с именем usersInRadius. После этого я проверил запрос по тексту, введенному в строке поиска, и добавил эти результаты в массив с именем favoriteBooks. Я использовал их как Set и безуспешно пытался сравнить содержащиеся в них элементы, используя функцию .intersection(), и получаю предупреждение

Результат вызова на «пересечение» не используется

Затем я помещаю окончательные результаты этой функции в массив с именем finalResults для отображения в collectionView.

Поиск работает, и я получаю книги о Гарри Поттере из массива finalResults, но фильтрация для близких мне пользователей не фильтрует все. Я думаю, что проблема возникает здесь на шаге 19:

favoriteBooksAsSet.intersection(usersInRadiusAsSet) // I get the warning message above

Он фильтрует неправильно. Вот код ниже.

let radius: Double = 5.0
let usersInRadius = [SearchModels] // an arr of all the users in the vicinity 
let favoriteBooks = [SearchModels] // an arr of all the results that contain the searchText
let finalResults = [SearchModels] // the final array that will display the results of the users in the vicinity with the search text by comparing the 2 above arrays as Sets

// 1. user enters text into the searchBar
func updateSearchResults(for searchController: UISearchController) {

    // 2. the text is Harry Potter
    guard let searchText = searchController.searchBar.text?.lowercased() else { return }

    // 3. look for all the users in the devices proximity
    getAlltheUsersInTheChosenRadius(radius: radius, searchText: searchText)
} 

func getAlltheUsersInTheChosenRadius(radius: Double, searchText: String) {

    // 4. check for location authorization
    if (CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
        CLLocationManager.authorizationStatus() ==  .authorizedAlways) {

        currentLocation = locationManager.location

        // 5. get the device's lat and lon
        let myLat = currentLocation.coordinate.latitude
        let myLon = currentLocation.coordinate.longitude

        // 6. use them to create a CLLocation
        let center = CLLocation(latitude: myLat, longitude: myLon)

        // 7. create the geoFire node to search on
        let geofireRef = Database.database().reference().child("users_location")
        let geoFire = GeoFire(firebaseRef: geofireRef)

        // 7. center in a 5 meter radius
        let circleQuery = geoFire.query(at: center, withRadius: radius)

        // 8. get the .keyEntered info
        let queryHandler = circleQuery.observe(.keyEntered, with: {
            (key: String!, location: CLLocation!) in

            // 9. create a SearchModel object and set the key to the userId's key and the location to the location
            let searchModel = SearchModel()
            searchModel.userId = key
            searchModel.location = location

            // 10. append these objects to an array of all the users who are in the vicinity      
            self.usersInRadius.append(searchModel)
        })

        // 11. geoFire is done now query the searchText
        circleQuery.observeReady({

            self.queryTheSearchFavoriteBooksNode(searchText: searchText)
        })
    }
}

func queryTheSearchFavoriteBooksNode(searchText: searchText) {

    // 12. set the ref for the searchFavoriteBooks to search on
    let favoriteBooksRef = Database.database().reference().child("searchFavoriteBooks").queryOrdered(byChild: "titleLowercased").queryStarting(atValue: searchText).queryEnding(atValue: searchText+"\u{f8ff}")

    favoriteBooksRef.observeSingleEvent(of: .value, with: { (snapshot) in

        guard let dictionaries = snapshot.value as? [String: Any] else {
            self.finalResults.removeAll()
            self.collectionView.reloadData()
            return
        }

        // 14. grab all the key/values pairs that have a value named "harry potter"
        dictionaries.forEach({ (key, value) in

            guard let dict = value as? [String: Any] else { return }

            // 15. init a SearchModel with the values from the dict
            let searchModel = SearchModel(dict: dict)

            // 16. check if the result is in the favoriteBooks array
            let isContained = self.favoriteBooks.contains(where: { (post) -> Bool in
                return searchModel.userId == post.userId
            })

            // 17. if it's not in the favoriteBooks array the append it to it
            if !isContained {
                self.favoriteBooks.append(searchModel)

                if self.favoriteBooks.count > 1 {

                    // 18. if there is more then 1 item in the favoriteBooks then cast it as a Set and also cast the userInRadius from step 10 as a Set
                    let favoriteBooksAsSet = Set(self.favoriteBooks)
                    let usersInRadiusAsSet = Set(self.usersInRadius)

                    // 19. compare the items in both sets and remove what I don't want. This ISN'T working
                   favoriteBooksAsSet.intersection(usersInRadiusAsSet)

                    // 20. append the results from the favoriteBooksAsSet in step 19 to the final finalResults which should display the UISearchController's results
                    self.finalResults.append(contentsOf: Array(favoriteBooksAsSet))
                }
                self.collectionView?.reloadData()
            }
        })
    })
}

// this is the SearchModel
class SearchModel: : Equatable, Hashable {

    var hashValue: Int {
        guard let uid = userId, let loc = location else {
            return Int(arc4random())
        }
        return uid.djb2hash ^ loc.hashValue
    }

    var postId: String?
    var title: String?
    var userId: String?
    var location: CLLocation?
    var lat: CLLocationDegrees?
    var lon: CLLocationDegrees?

    convenience init(dict: [String: Any]) {
        self.init()

        postId = dict["postId"] as? String
        title = dict["title"] as? String
        userId = dict["userId"] as? String
        location = dict["location"] as? CLLocation
        lat = dict["lat"] as? CLLocationDegrees
        lon = dict["lon"] as? CLLocationDegrees
    }

    static func == (lhs: SearchModel, rhs: SearchModel) -> Bool {
        return lhs.userId == rhs.userId
    }
}

// String extension for the hash value in the SearchModel
extension String {
    var djb2hash: Int {
        let unicodeScalars = self.unicodeScalars.map { $0.value }
        return unicodeScalars.reduce(5381) {
            ($0 << 5) &+ $0 &+ Int($1)
        }
    }
}

1 Ответ

0 голосов
/ 31 октября 2018

Я получил ответ от этого SO ответа

Проблема заключалась в том, что я разделил наборы на этапах 18 и 19:

// 18. if there is more then 1 item in the favoriteBooks then cast it as a Set and also cast the userInRadius from step 10 as a Set
let favoriteBooksAsSet = Set(self.favoriteBooks)
let usersInRadiusAsSet = Set(self.usersInRadius)

// 19. compare the items in both sets and remove what I don't want. This ISN'T working
favoriteBooksAsSet.intersection(usersInRadiusAsSet)

// 20. append the results from the favoriteBooksAsSet in step 19 to the final finalResults which should display the UISearchController's results
self.finalResults.append(contentsOf: Array(favoriteBooksAsSet))
            }

Корректирующее решение состояло в том, чтобы использовать то, что было из ответа SO, и объединить оба массива в качестве Наборов, а затем, независимо от результатов, полученных методом пересечения, использовать это для шага 20:

// steps 18 and 19 combined
let tempSet = Set(self.favoriteBooks).intersection(Set(self.usersInRadius))

// 20. append the results from the tempSet in step 18 and 19 to the final finalResults which should display the UISearchController's results
self.finalResults.append(contentsOf: Array(tempSet))
...