Matteo Villa Matteo Villa - 1 year ago 141
JSON Question

I need to fetch a JSON in a URL

Answer Source

I suggest using a third party framework like Alamofire The native Swift networking is rather complicated, especially for beginners, because Swift is type-safe language and a JSON object can have nesting etc. that can only be seen after actually fetching of the object.

The good thing is that Alamofire can be easily installed with CocoaPods and it is actively being developed. Here is an example of a request made with Alamofire's 4.0 version for Swift 3 to fetch a JSON object from a url called yourUrl:

Alamofire.request("https://yourUrl").responseJSON { response in
  print(response.request)  // original URL request
  print(response.response) // HTTP URL response
  print(     // server data
  print(response.result)   // result of response serialization

  if let json = response.result.value {
    print("JSON: \(json)")
    // do something with json here

You can then use another third party framework like SwiftyJSON to parse the JSON you retrieve - especially if it has a complicated structure. But sadly there is no update in sight for Swift 3 so I guess we have to wait and see how this pans out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download