2017-02-24 1 views
1

firebase 백엔드에서 데이터를 검색하려고합니다. 각 항목의 사용자 이름은 lat이고 long입니다. 다른 stackoverflow 질문에서 보면 CoreLocation은 가장 가까운 위치로 정렬해야한다고 생각합니다. 사용하려고 시도한 distancefrom (또는 오히려 distance (:) 메서드) 메서드입니다. 의도 한대로 작동하지 않는 것 같습니다. 내가 뭘 잘못하고 있는지 궁금해.Swift - Firebase DB에서 가져온 데이터로부터 가장 가까운 위치로 정렬

import UIKit 
import Firebase 
import FirebaseDatabase 
import MapKit 
import CoreLocation 

class RequestVC: UITableViewController, CLLocationManagerDelegate { 

    var locationManager = CLLocationManager() 
    var sellerUserNames = [String]() 
    var requestLocations = [CLLocationCoordinate2D]() 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "backToMain" { 
      self.navigationController?.navigationBar.isHidden = true 
     } 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestWhenInUseAuthorization() 
     locationManager.startUpdatingLocation() 

     let databaseRef = FIRDatabase.database().reference() 
     databaseRef.child("Sell_Request").observe(FIRDataEventType.childAdded, with: { (FIRDataSnapshot) in 

      if let data = FIRDataSnapshot.value as? NSDictionary { 
       if let name = data[Constants.NAME] as? String { 
        if let lat = data["latitude"] as? Double { 
         if let long = data["longitude"] as? Double { 

          print("\(self.sellerUserNames) Location: Latitude: \(lat), Longitude: \(long)") 

          self.sellerUserNames.append(name) 
          self.requestLocations.append(CLLocationCoordinate2D(latitude: lat, longitude: long)) 

          self.tableView.reloadData() 

         } 
        } 
       } 
      } 
     }) 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     } 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return sellerUserNames.count 
    } 


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
     let location = locationManager.location?.coordinate 

     let buyerLocation = CLLocation(latitude: (location?.latitude)!, longitude: (location?.longitude)!) 
     let sellerLocation = CLLocation(latitude: requestLocations[indexPath.row].latitude, longitude: requestLocations[indexPath.row].longitude) 

     let distance = buyerLocation.distance(from: sellerLocation)/1000 

     let roundedDistance = round(distance * 100)/100 

     let distanceInMiles = roundedDistance * 0.621 
     let roundedDistanceInMiles = round(distanceInMiles * 1000)/1000 


     cell.textLabel?.text = sellerUserNames[indexPath.row] + " - \(roundedDistanceInMiles) miles away" 

     return cell 
    } 
} 
+0

코드를 [MWE] (http://stackoverflow.com/help/mcve)로 트리밍 할 수 있습니까? 파이어베이스에 아무런 문제가 없으므로 보여줄 필요가 없습니다. 좌표 목록과 테이블 뷰에 표시 할 순서를 표시하십시오. –

+0

조금 어둡게 만들었습니다. 죄송합니다. – user2411290

답변

-1

GeoFire을 사용해보세요. 해결 방법이 있지만 코코아포드에서는 작동하지 않습니다.

관련 문제