TableView根据距离当前位置的距离进行排序(解析来自JSON的位置)
问题描述:
在xCode中,我尝试对TableView内的对象进行排序,以便它们按照与用户的接近程度排列。我看到这个问题,但我似乎无法弄清楚如何将它实现到我的项目中,因为我通过JSON文件解析位置。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()
}
}
答
在位置模型中定义了一个名为0的属性。这是距用户当前位置的距离。
var distance: Double {
get {
return CLLocation(latitude: latitude , longitude: longitude).distance(from: userLocation)
}
}
这将返回距离CLLocationDistance
,但你可以使用它作为双,因为它使易于使用,同时排序。
现在你可以按照升序排列locations
这样并刷新数据
var locations = [Location]()
locations.sort { $0.distance < $1.distance }
self.tableView.reloadData()
谢谢!这可能是一个noob错误,但是我收到一个错误,说“使用未解析的标识符'userLocation'”。这是因为我需要定义userLocation?我应该在哪里做这件事? – joshlorschy
@joshlorschy您必须在全局或某个共享实例中保存用户位置。这取决于你 – Jaydeep
我可以在Location.swift模型中做到吗?或者它应该在AppDelegate中? – joshlorschy