Matteo Villa Matteo Villa - 4 months ago 56
JSON Question

I need to fetch a JSON in a URL


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.