2017-06-11 77 views
0

我幾次問這個看似非常簡單直接的問題,從未得到過解決方案。在swift 3中從url中獲取mySql數據 - 再次

我有一個網址,以獲取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" 

我的理解是urlDictAny型。我對麼?

我最大的問題是我怎麼能(鑄造或convet)urlDict,這樣我可以訪問使用鍵=>值的價值?就像這樣:

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

我是一個新手到斯威夫特,所以我做這個作爲一個練習,任何幫助將不勝感激。

回答

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) 
+0

太謝謝你了。最後,有一個答案對我愚蠢的頭腦有意義! :) – Tony