Получение дубликатов местоположений из базы данных Geofire / Firebase на Swift 5 - PullRequest
0 голосов
/ 27 сентября 2019

Я новичок в Firebase и Geofire.Я посмотрел онлайн и не смог найти ничего, что помогло бы мне.Было несколько статей, но они были в java и т. Д.

В настоящее время я использую swift 5 с базой данных Firebase Realtime.Мое приложение находит ближайшие летные школы рядом с пользователем.Я могу сохранить местоположение пользователей, а затем получить ближайшую летную школу.После извлечения летной школы я показываю маркер и показываю текст в виде таблицы.

У меня проблема с моим кодом.Находит дубликаты летной школы.Я не знаю, почему он находит дубликаты.Я читал в Интернете, и было несколько решений, но не знаю, как правильно реализовать это в моем коде.Я везде читал об этой проблеме, но это не совсем понятно.

Я чувствую, что моя проблема со мной, я звоню

let geoFire = GeoFire(firebaseRef: ref.child("users"))

и затем звоню

let geo = GeoFire(firebaseRef: ref.child("flightschool"))

Нижеэто мой код и картинки.Я новичок в спешке, поэтому, пожалуйста, не разрывайте меня слишком сильно.Я знаю, что мой код в настоящее время не оптимизирован вообще.

Заранее спасибо!

База данных Firebase Дубликаты школ

Class mapViewViewController: UIViewController, CLLocationManagerDelegate {

var FlightSchool = [flightSchool]() 
var ref = Database.database().reference()

let latitude = [Double]()
let longitude = [Double]()
let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self

    //For the use when the application is open or in background
    locationManager.requestAlwaysAuthorization()
    //For the use when the application is open
    locationManager.requestWhenInUseAuthorization()
    tableView.dataSource = self
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    guard status == .authorizedWhenInUse else { return }
    locationManager.startUpdatingLocation()
    mapView.isMyLocationEnabled = true
    mapView.settings.myLocationButton = true
    }

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.first else { return }
    mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 13, bearing: 0, viewingAngle: 0)
    locationManager.stopUpdatingLocation()

  // Saving users location in "users"
    let geoFire = GeoFire(firebaseRef: ref.child("users"))
    let user = Auth.auth().currentUser?.uid
    if let uid = user {
        geoFire.setLocation(location, forKey: uid) { (error) in
        if (error != nil) {
            print("An error occured: \(String(describing: error))")
        } else {
            print("Saved location successfully!")
        }
    }
}

// Find location from Realtime Firebase Database and then show only markers near the user
    let geo = GeoFire(firebaseRef: ref.child("flightschool"))
    let center = location
    let circleQuery = geo.query(at: center, withRadius: 10)
    _ = circleQuery.observe(GFEventType.keyEntered, with: { (key: String!, location: CLLocation!) in
        print ("FOUND KEY: ",key!," WITH LOCATION: ",location!)

        let locationObj = location as CLLocation
        let coord = locationObj.coordinate
        let longitude = coord.longitude //Latitude & Longitude as String
        let latitude = coord.latitude
        let schoolName = key

        //Needed to setup the tableview
        let keyText = schoolName
        let FlightSchool = flightSchool(keyText: keyText!)
        self.FlightSchool.append(FlightSchool)

        //Needed to setup the markers
        let position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        let marker = GMSMarker(position: position)
        marker.tracksInfoWindowChanges = true
        marker.title = schoolName
        marker.appearAnimation = GMSMarkerAnimation.pop
        marker.map = self.mapView
        self.tableView.reloadData()

      })   
    }
  }
...