Im using Alamofire to get a table of trucks. Results are handled using SwiftyJSON. One of the columns is the coordinate of each truck.
I would like to compare the trucks coordinate with the users current location. I can already do the calculation. I was thinking of adding the distance calculated into the same JSONObject as a new field with the intention of sorting by distance but I cant seem to set a new value at all.
Setting a json object is not working at all. Below is my code. I commented the part where it doesnt work. I dont get warnings or errors. If i print that out i just get a blank row. Please help. Thanks in advance. Am I doing it right? Any suggestions on how I could best sort the list by distance given the truck coordinates in the results and user location on device?
Alamofire.request(.POST, Ftf.endPoint(), parameters: params).responseJSON { response in
if response.result.value != nil{
let obj = JSON(response.result.value!)
self.jsonObj = obj
//ATTEMPT TO SORT THE JSON OBJECT
print("Begin Sorting Object")
print("User located at \(self.MyLocation)")
for (key,subJson):(String, JSON) in self.jsonObj {
let truckloc = subJson["truckLocation"].stringValue
print("This truck is at \(truckloc)")
let coords = truckloc
var coord = coords.componentsSeparatedByString(",")
let lat = coord[0]
let lon = coord[1]
let truckLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((lat as NSString).doubleValue, (lon as NSString).doubleValue)
let point1 = MKMapPointForCoordinate(self.MyLocation)
let point2 = MKMapPointForCoordinate(truckLocation)
let distance = MKMetersBetweenMapPoints(point1, point2)/1000
let distanceStr = NSString(format: "%.1f", distance)
print("Distance of truck from user is \(distanceStr)")
//THIS LINE HERE DOESNT WORK. NO ERROR NO WARNINGS. JUST NOTHING HAPPENS
self.jsonObj[key]["distance"].string = "\(distanceStr)"
}
self.activityIndicator.stopAnimating()
self.tableView.reloadData()
self.ftfRefresh.endRefreshing()
}else{
self.presentViewController(Ftf.generalAlert("No network connection found"), animated: true, completion: nil)
}
}
Try this,
self.jsonObj[key]["distance"] = JSON("\(distanceStr)")
Sample example,
var json = JSON(["1":"2"])
print(json)
json["1"] = JSON("3")
print(json)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With