TableView按当前位置的距离排序(从JSON解析位置)

时间:2017-08-11 05:24:56

标签: swift xcode sorting distance cllocationmanager

在xCode中,我试图对TableView中的对象进行排序,以便它们按照与用户的接近程度排列。我已经看到了这个问题,但是当我通过JSON文件解析位置时,我似乎无法弄清楚如何将它实现到我的项目中。

我需要做些什么来计算用户位置和每个位置对象位置之间的距离?然后,我如何按升序对TableView中的对象进行排序?

这是Location.swift模型:

import Foundation
import MapKit
import CoreLocation

var currentLocation:CLLocation?

class Location: NSObject {
    var id: String = ""
    var name: String = ""
    var type: String = ""
    var location: String = ""
    var image: String = ""
    var activity: String = ""
    var rating: String = ""
    var latitude: Double = 0.0
    var longitude: Double = 0.0
    var distance: Double {
        get {
            return CLLocation(latitude: latitude, longitude: longitude).distance(from: currentLocation!)
        }
    }

    init(locationInfo:[String:Any]) {
        self.id = locationInfo["id"] as! String
        self.name = locationInfo["name"] as! String
        self.type = locationInfo["type"] as! String
        self.location = locationInfo["location"] as! String
        self.image = locationInfo["image"] as! String
        self.activity = locationInfo["activity"] as! String
        self.latitude = locationInfo["latitude"] as! Double
        self.longitude = locationInfo["longitude"] as! Double
}

    public var coordinate: CLLocationCoordinate2D { get {
        let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        return coordinate
        }
    }

}

以下是LocationTableViewController.swift的相关部分:

class LocationTableViewController: UITableViewController {

    var locations = [Location]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let locationService: LocationService = LocationService()
        locations = locationService.readLocation()
        locations.sort { $0.distance < $1.distance }
        self.tableView.reloadData()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }

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

        let cellIdentifier = "cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LocationTableViewCell

        // Configure the cell
        cell.nameLabel.text = locations[indexPath.row].name
        cell.thumbnailImageView.image = UIImage(named: locations[indexPath.row].image)
        cell.locationLabel.text = locations[indexPath.row].location
        cell.typeLabel.text = locations[indexPath.row].type
        return cell
    }
}

这是我在AppDelegate中实现的,用于捕获用户的位置:

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    var window: UIWindow?
    var locationManager:CLLocationManager!
    private var currentCoordinate:CLLocationCoordinate2D?
    var currentLocation:CLLocation?

    static var locations: Array<Location> = Array()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // Location Manager
        func setupLocationManager() {
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            self.locationManager?.requestAlwaysAuthorization()
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            locationManager?.startUpdatingLocation()
            }
        }

        return true
    }

    // Location Manager
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if currentLocation == nil {
            currentLocation = locations.last
            locationManager?.stopMonitoringSignificantLocationChanges()
            let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
            print("locations = \(locationValue)")
            locationManager?.stopUpdatingLocation()
        }
    }

1 个答案:

答案 0 :(得分:0)

在您的位置模型中定义了另一个名为distance的属性。这是与用户当前位置的距离。

var distance: Double {
        get {
            return CLLocation(latitude: latitude , longitude: longitude).distance(from: userLocation)
        }
    }

这会返回CLLocationDistance中的距离,但您可以将其用作Double,因为它在排序时很容易。

现在您可以像这样在升序数组中排序locations并重新加载数据

var locations = [Location]()

locations.sort { $0.distance < $1.distance  }

self.tableView.reloadData()