我正在使用 Alamofire 获取一张卡车表。结果使用 SwiftyJSON 处理。其中一列是每辆卡车的坐标。
我想将卡车坐标与用户当前位置进行比较。我已经可以计算了。我正在考虑将计算出的距离添加到与新字段相同的 JSONObject 中,目的是按距离排序,但我似乎根本无法设置新值。
设置 json 对象根本不起作用。下面是我的代码。我评论了它不起作用的部分。我没有收到警告或错误。如果我打印出来,我只会得到一个空白行。请帮忙。提前致谢。我做对了吗?鉴于结果中的卡车坐标和用户在设备上的位置,关于如何按距离对列表进行最佳排序有什么建议吗?
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)
}
}
最佳答案
试试这个,
self.jsonObj[key]["distance"] = JSON("\(distanceStr)")
示例,
var json = JSON(["1":"2"])
print(json)
json["1"] = JSON("3")
print(json)
关于json - SwiftyJson 无法设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788544/