2017-08-09 111 views
1

我是Swift新手, 我想從服務器響應中獲取緯度和longitde的值。從服務器響應中獲取價值swift

我該如何獲得價值?

這裏是我的代碼:

WebServiceHelper.sharedInstance.makeWebServiceCall(urlAddress: "http://jsonplaceholder.typicode.com/users/1", requestMethod: "GET", params: ["Key" : "value"], Success: { (JSON:Any) in 

      print("Success Received data is: \(JSON)") 

     }, Error: { (JSON:Any) in 

      print("Error Received data is: \(JSON)") 

     }) { (JSON:Any) in 

      print("Header Received data is: \(JSON)") 
     } 

我能夠獲得服務器效應初探那就是:

Success Received data is: { 
    "id": 1, 
    "name": "Leanne Graham", 
    "username": "Bret", 
    "email": "[email protected]", 
    "address": { 
    "street": "Kulas Light", 
    "suite": "Apt. 556", 
    "city": "Gwenborough", 
    "zipcode": "92998-3874", 
    "geo": { 
     "latitude": "-37.3159", 
     "longitude": "81.1496" 
    } 
    }, 
    "phone": "1-770-736-8031 x56442", 
    "website": "hildegard.org", 
    "company": { 
    "name": "Romaguera-Crona", 
    "catchPhrase": "Multi-layered client-server neural-net", 
    "bs": "harness real-time e-markets" 
    } 
} 

我如何獲得?

+0

JSONSerialization,之後轉換成你的模型 –

+0

檢查這個問題https://stackoverflow.com/questions/45019869/what-am -i-doing-wrong-in-my-json-post/45020163#45020163 –

+0

你可以幫我理解語法嗎? –

回答

1

你可以嘗試這樣得到Lat Long網:

if let result = JSON as? [String:AnyObject]{ 
     let address = result?["address"] as? [String:AnyObject] 
     let geo = address?["geo"] as? [String:AnyObject] 
     print(geo?["lng"]) 
     print(geo?["lat"]) } 
+0

我試過這段代碼,但是如果存在'JSON'的條件值,控件不會進入裏面 –

+0

行!那麼你可以使用這個沒有「如果」條件。 –

+0

當我寫這個'let address = JSON [「address」]爲?時,會出錯? [String:AnyObject]' –