如何从网页中检索JSON数据

时间:2016-09-13 05:07:31

标签: ios swift

我的网页在一行中显示建设性数据,特别是让我的应用程序检索它。

JSON

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

此信息位于页面中,请点击此处查看:http://www.gogrex.com/Sandbox/startloc.json

如何将其作为JSON检索到我的应用中?我看了很多例子,但仍然无法解决它。

1 个答案:

答案 0 :(得分:1)

Swift 3.x

SELECT a.CustomerID, a.Coupon_Code, a.DateOfUsege, b.Text
FROM `used_bonus_codes` a
INNER JOIN `customer_notes` b
  ON a.CustomerID = b.CustomerID
  AND b.Text LIKE CONCAT('%', a.Coupon_Code, '%')

Swift 2.3

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 ?? "nil")
                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: Any] {
                    let latString = jsonDict["lat"] as? String
                    let longString = jsonDict["long"] as? String
                    print("latitude = ", latString ?? "nil")   // 345.12
                    print("longitude = ", longString ?? "nil")  // 1234..45  ( you need to fix this value)
                    print(Double(latString ?? "nil") ?? "nil")  // Optional(345.12)
                    print(Double(longString ?? "nil") ?? "nil") // nil
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }.resume()
    }
}

不要忘记编辑您的info.plist以添加您的网域

enter image description here

相关问题