的 Swift 3.x 强>
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() } }
的 斯威夫特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() } }
不要忘记编辑info.plist以添加您的网域