Tony Tony -4 years ago 106
Swift Question

Getting mySql data from url in swift 3 - again

I have asked this seemingly very simple and straight forward question a few times now, never got a solution.

I have a url to obtain mySql data
// 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.


Then I move on to extracting the data:
//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"

My understanding is urlDict is of a Any type. Am I correct?

This is the un-annswered question. My biggest question is how can I (cast or convet) urlDict so that I can access the value using key=>value ????? Like this urlDict!["Address"] Outputs "1 Infinite Loop Cupertino, CA"
urlDict!["Latitude"] Outputs "37.331741"...

I am a newbie to Swift so I am doing this as an exercise, any help will be greatly appreciated.

Answer Source

Your JSON response returns an Array of Dictionary objects. So you just need to cast correctly.

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"])
    }
}

Output:

Optional(-122)
Optional(37.331741)
Optional(1 Infinite Loop Cupertino, CA)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download