Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Fetch mySql data to iOS in swift 3

dickthedevdickthedev Posts: 214Registered Users @ @
edited June 6 in iOS SDK Development
Hello, as a coding exercise, I have the following code to fetch data from my Site
// 1. get url
let url = URL(string:"http://www.mobwebplanet.com/phpWebService/sample.php")
then
// 2. Fetch data from url
let data = try? Data(contentsOf: url!)
create a dictionary from the json data
//3. Create a dictionary from data
let urlDict = try? JSONSerialization.jsonObject(with: data!, options: [])

the output in playground is this
[["Latitude": "37.331741", "Address": "1 Infinite Loop Cupertino, CA", "Name": "Apple", "Longitude": "-122"]] 

which looks just fine. However, when I tried to use count, I get this error:
print("The dictionary has", urlDict.count, "entries.")

I get this error:
Value of type 'Any?' has no member 'count'

Why is that? Thanks.

Replies

  • BrianSlickBrianSlick Treadmill Desk Ninja Posts: 10,689Tutorial Authors, Registered Users @ @ @ @ @ @ @ @
    The method is defined as:
    class func jsonObject(with data: Data, 
                  options opt: JSONSerialization.ReadingOptions = []) throws -> Any
    

    So "Any" is the return type.
    Professional iOS App Development. Available for hire.
    BriTer Ideas LLC - WWW | Facebook | Twitter | LinkedIn

    BTIKit | BTICoreDataKit | SlickShopper 2 | Leave a PayPal donation
  • dickthedevdickthedev Posts: 214Registered Users @ @
    Thanks for the reply. So the return type is Any. So does it mean urlDict has to be casted into an dictionary that I can use .count and also have access to the key to get the value? How to go about doing that?
  • dickthedevdickthedev Posts: 214Registered Users @ @
    In other words, I thought In step 3. Create a dictionary from data
    let urlDict = try? JSONSerialization.jsonObject(with: data!, options: [])
    urlDict is already a dictionary. Obvious I am wrong. What process I eed to get the data in to the correct type so that I can have access to its key->value and access its methods?
Sign In or Register to comment.