【发布时间】:2016-03-04 05:20:41
【问题描述】:
我正在使用 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"] = "\(distanceStr)" -
是的。如果我这样做,我会得到一个“无法将'String'类型的值分配给'JSON'类型。没用。
-
也许
self.jsonObj[key]["distance"] as! String = "\(distanceStr)"
标签: json swift sorting alamofire