Steve Law Steve Law - 2 months ago 8
Swift Question

How to retrieve JSON data from webpage

My webpage displays a constructive data in a single line, specifically to let my app retrieve it.

JSON

[{"long":"1234..45","lat":"345.12"}]


This information is in a page, click here to see: http://www.gogrex.com/Sandbox/startloc.json

How do I retrieve it into my app as a JSON? I have looked thru many examples but still cannot solve it.

Answer

Xcode 8 GM • Swift 3

Try like this:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // create your get url
        let getURL = URL(string: "http://www.gogrex.com/Sandbox/startloc.json")!
        // use URLSession to get the data from your website
        URLSession.shared.dataTask(with: getURL) { (data, response, error) in
            guard let data = data, error == nil else {
                print(error?.localizedDescription)
                return
            }
            // you need to serialize your data using  JSONSerialization jsonObject(with:options)
            do {
                if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [Any],
                let jsonDict = jsonArray.first as? [String:AnyObject] {
                    let latString = jsonDict["lat"] as? String ?? ""
                    let longString = jsonDict["long"] as? String ?? ""
                    print("latitude = ", latString)   // 345.12
                    print("longitude = ", longString)  // 1234..45  ( you need to fix this value)
                    print(Double(latString))  // Optional(345.12)
                    print(Double(longString)) // nil
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Xcode 8 GM • Swift 2.3

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let getURL = NSURL(string: "http://www.gogrex.com/Sandbox/startloc.json")!
        NSURLSession.sharedSession().dataTaskWithURL(getURL) { (data, response, error) in
            guard let data = data where error == nil else {
                print(error?.localizedDescription)
                return
            }
            do {
                if let jsonArray = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [AnyObject],
                    let jsonDict = jsonArray.first as? [String:AnyObject] {
                    let latString = jsonDict["lat"] as? String ?? ""
                    let longString = jsonDict["long"] as? String ?? ""
                    print("latitude = ", latString)   // 345.12
                    print("longitude = ", longString)  // 1234..45  ( you need to fix this value)
                    print(Double(latString))  // Optional(345.12)
                    print(Double(longString)) // nil
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Don't forget to edit your info.plist to add your web domain

enter image description here

Comments