如何使用JSON文件中的信息填充数组并计算距离?

时间:2016-08-19 16:26:12

标签: ios json location

我在这里有一个JSON文件:

     {
      "People": [{
       "A1": "New York",
       "B1": "ShoppingMall1",
       "C1": "43.0757",
       "D1": "23.6172"
       },
       {
       "A1": "London",
       "B1": "ShoppingMall2",
       "C1": "44.0757",
       "D1": "24.6172"
       }, {
       "A1": "Paris",
       "B1": "ShoppingMall3",
       "C1": "45.0757",
       "D1": "25.6172"
       }, {
       "A1": "Bern",
       "B1": "ShoppingMall4",
       "C1": "41.0757",
       "D1": "21.6172"
       }, {
       "A1": "Sofia",
       "B1": "ShoppingMall5",
       "C1": "46.0757",
       "D1": "26.6172"

       }
       ]
       }

从这个JSON文件中我必须获取购物中心的名称和坐标,并将它们填充到一个数组中。我想在Table View Cells中使用这个数组。主要想法是围绕用户当前位置计算最近的购物中心。在这里,我计算用户的当前位置。

@IBAction func LocateMe(sender: AnyObject) {
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()




   }
   func  locationManager(manager: CLLocationManager, didUpdateLocations      locations: [CLLocation]) {
let userlocation: CLLocation = locations[0] as CLLocation
manager.stopUpdatingLocation()
let location = CLLocationCoordinate2D(latitude: userlocation.coordinate.latitude, longitude: userlocation.coordinate.longitude)
let span = MKCoordinateSpanMake(0.5, 0.5)
let region = MKCoordinateRegion(center: location, span: span)

   }
   let distanceMeters = userlocation.distanceFromLocation(CLLocation(latitude: ??,longitude: ??))
let distanceKilometers = distanceMeters / 1000.00
let roundedDistanceKilometers = String(Double(round(100 * distanceKilometers) / 100)) + " km"

但是我不知道如何把所有的商场坐标和比较它们。我也不知道如何将它们填充到我需要用于Table View Cell的数组中。我是swift的新手我如果有人可以帮助我,我会很高兴的。

1 个答案:

答案 0 :(得分:0)

我一直在研究你的问题,这是我的结果,

首先,我建议您使用一个JSON framework,例如SwiftyJSON,但我不使用任何因为我不知道您是否愿意,所以

首先我们需要使用此代码加载我们的json

let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
let JSONData = NSData(contentsOfFile: pathForPlist)

在我们需要解析这些数据并转换为JSONObject

之后
let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

并使用Dictionary中的初始化程序转换为正确的对象,请注意我们使用NSJSONReadingOptions.MutableContainers,因为我们的json是一个字典数组

这是完整的代码,请注意我为您的数据类型定义了一个名为ObjectShop的类,以帮助您稍后进行计算

import UIKit
import MapKit

class ObjectShop
{
    var A1 = ""
    var B1 = ""
    var C1 = ""
    var D1 = ""

    init?(dict:[String:AnyObject])
    {
        A1 = dict["A1"] as! String
        B1 = dict["B1"] as! String
        C1 = dict["C1"] as! String
        D1 = dict["D1"] as! String
    }

    func getCoordenate2D() -> CLLocationCoordinate2D
    {
        return CLLocationCoordinate2D(latitude: Double(self.C1)!, longitude: Double(self.D1)!)
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let pathForPlist = NSBundle.mainBundle().pathForResource("JSON", ofType: "json")!
        let JSONData = NSData(contentsOfFile: pathForPlist)
        do
        {
            var objects = [ObjectShop]()
            let JSONObject = try NSJSONSerialization.JSONObjectWithData(JSONData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
            print(JSONObject)
            for dic in JSONObject["People"] as! [[String:AnyObject]] {
                print(dic)
                let objc = ObjectShop(dict: dic)
                objects.append(objc!)
            }

            for object in objects {
                print(object.getCoordenate2D())
            }
        }
        catch _
        {

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我希望这会对你有所帮助,如果你有任何疑问,请告诉我