How to populate an array with information from JSON File and calculate distance?

你说的曾经没有我的故事 提交于 2019-12-18 09:46:51

问题


I have a JSON File here:

     {
      "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"

       }
       ]
       }

and from this JSON File I have to take the names and the coordinates of the shopping malls and populate them into an array. This array I want to use in Table View Cells. The main idea is calculating the nearest shopping malls around the user's current location. Here I calculate the user's current location.

@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"

But I do not know how to take all of the shopping malls coordinates and compare them.I also do not how to populate them into an array which I need to use for the Table View Cells.I am new in swift and I will be glad if someone can help me with that.


回答1:


I had been working on your question and this are my results,

First of all I recommend you to use one JSON framework such as SwiftyJSON but I don't use any because I don't know if you want to, so

first we need to load our json using this code

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

after we need to parse this data and convert to JSONObject

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

and convert to properly Objects using an initializer from Dictionary, note that we use NSJSONReadingOptions.MutableContainers because our json is an array of dictionaries

this is the full code, note that I define a class for your data type named ObjectShop to help with the calculation later

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.
    }


}

I hope this helps you, let me know if you have any question



来源:https://stackoverflow.com/questions/39043783/how-to-populate-an-array-with-information-from-json-file-and-calculate-distance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!