I'm having trouble succinctly pulling data from an api, adding the users current location into the object and then sorting the data based on the calculated distance.
The stackoverflow questions don't quite answer the problem I'm facing. See here: How to sort posts read from JSON server file in Swift.
I'm currently loading api data from Alamofire and rendering that data with a UITableViewController.
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.title = q.capitalizedString
Alamofire.request(.GET, "http://www.thesite.com/api/v1/things", parameters: ["q" : q])
.responseJSON { response in
let JSONObject = JSON(response.result.value!)
self.results = JSONObject["things"]
for (key, _) in self.results {
let intKey: Int = Int(key)!
var thisItem: JSON = self.results[intKey]
let geoLat = thisItem["place"][0]["location"]["geo"][1].double ?? 37.763299
let geoLong = thisItem["place"][0]["location"]["geo"][0].double ?? -122.419356
let destination = CLLocation(latitude: geoLat, longitude: geoLong)
let setLocation = CLLocation(latitude: self.currentLocation.latitude, longitude: self.currentLocation.longitude)
let distanceBetween: CLLocationDistance = destination.distanceFromLocation(setLocation)
thisItem["distance"].double = distanceBetween
self.results[intKey] = thisItem
}
self.tableView.reloadData()
}
}
I get the data from the api and successfully add the distance between the user's location and the destination of the place.
However, now I need to sort the JSON object (SwiftyJSON) from lowest to highest distance. This is where I'm stuck.
the data structure at the point the tableView (as JSON object) is reloaded is essentially:
results = [
{"title": "Chai", "distance": "1245.678575"},
{"title": "Espresso", "distance": "765845.678575"},
{"title": "Drip Coffee", "distance": "23445.678575"}
...
]
How would I be able to either: 1) convert the object to NSArray and sort; or 2) just sort the object? When would be the best place to do the distance add and sort - should I do it before converting to the JSON object.
Any help is appreciated! Thanks!