Swift4:我想从我的位置按近似顺序重新排列 API 获取的 JSON



感谢您观看我的问题。

我的 iOS 应用程序流。当您按下类别按钮时,该类别中商店的数据将返回 JSON。纬度和经度包含在商店的数据中。基于这个纬度和经度,我想重新排列JSON的内容,以便您可以从我的位置按顺序显示商店。

我正在寻找示例代码,但找不到。

请告诉我。

谢谢。

JSON 数据

{
"id": 1,
"name": "Barth day",
"created_at": "2018-08-09 10:00:58",
"updated_at": "2018-08-09 10:00:58",
"stores": [
{
"id": 1,
"name": "Pink Cafe Tokyo",
"location": "Tokyo",
"price": "1000~3000",
"open_time": "10:00-14:00",
"closed_day": "月曜日",
"created_at": "2018-08-09 10:03:52",
"updated_at": "2018-08-09 10:03:52",
"tellNumber": "09012345678",
"lat": 35.662163,
"lng": 139.744629,
"pivot": {
"store_id": 1,
"category_id": 1
},
"tags": [
{
"id": 1,
"name": "Sweets",
"created_at": "2018-08-09 10:00:58",
"updated_at": "2018-08-09 10:00:58",
"pivot": {
"tag_id": 1,
"store_id": 1
}
},
{
"id": 13,
"name": "Pink Cafe",
"created_at": "2018-08-09 10:00:58",
"updated_at": "2018-08-09 10:00:58",
"pivot": {
"tag_id": 1,
"store_id": 13
}
},
{
"id": 14,
"name": "Concept Cafe",
"created_at": "2018-08-09 10:00:58",
"updated_at": "2018-08-09 10:00:58",
"pivot": {
"tag_id": 1,
"store_id": 14
}
}
],
"photos": [
{
"id": 1,
"store_id": 1,
"path": "photos/Pink%20Cafe%20Tokyo_0.jpeg",
"created_at": "2018-08-09 10:03:52",
"updated_at": "2018-08-09 10:03:52"
}
]
}
}

考虑到您有一个映射到商店的struct,其属性为 lat 和 lng,如下所示

struct Store {
// other attributes
var lat: CLLocationDegrees
var lng: CLLocationDegrees
}

并且您在名为 currentLocation 的属性中具有可用的当前位置。

现在在存储数组中,要根据与当前位置的距离对对象进行排序,您可以使用下面的代码

arrOfStores.sort { (obj1, obj2) -> Bool in
let a = CLLocation(latitude: obj1.lat, longitude: obj1.lng)
let b = CLLocation(latitude: obj2.lat, longitude: obj2.lng)
return currentLocation.distance(from: a) < currentLocation.distance(from: b)
}

现在,您的商店数组按升序排列,距离当前位置有距离。

最新更新