从swift 3中的url获取mySql数据 - 再次

时间:2017-06-11 13:51:31

标签: swift

我现在几次问这个看似非常简单直接的问题,从来没有得到解决方案。

我有一个获取mySql数据的网址

// 1. get url
let url = URL(string:"http://www.mobwebplanet.com/phpWebService/sample.php")

// 2. Fetch data from url
let data = try? Data(contentsOf: url!)
//playground Output is: 102 bytes. So obviously xcode gets the response data from the URL.

然后我继续提取数据:

//3. Create a dictionary from data:
let urlDict  = try? JSONSerialization.jsonObject(with: data!, options: [])

// playground Output is: [["Latitude": "37.331741", "Address": "1 Infinite Loop Cupertino, CA", "Name": "Apple", "Longitude": "-122"]]
print(urlDict!)

// playground Output is: "(\n        {\n        Address = "1 Infinite Loop Cupertino, CA";\n        Latitude = "37.331741";\n        Longitude = "-122";\n        Name = Apple;\n    }\n)\n"

我的理解是urlDict属于Any类型。我是对的吗?

我最大的问题是如何(投射或传送)urlDict以便我可以使用key =>值来访问该值?像这样:

 urlDict!["Address"] Outputs "1 Infinite Loop Cupertino, CA"
 urlDict!["Latitude"] Outputs "37.331741"...

我是Swift的新手,所以我这样做是为了锻炼,任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的JSON响应返回一个Dictionary对象数组。所以你只需要正确投射。

let urlString = "http://www.mobwebplanet.com/phpWebService/sample.php"
let url = URL(string: urlString)!

let data = try? Data(contentsOf: url)

if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
    for location in json! {
        print(location["Longitude"])
        print(location["Latitude"])
        print(location["Address"])
    }
}

输出:

Optional(-122)
Optional(37.331741)
Optional(1 Infinite Loop Cupertino, CA)