Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to retrieve json data from remote url using swift 4 for an array

Tags:

swift

I am trying to see what is the latest and greatest way to retrieve json data in swift 4 (using Codable structure).

I have the following json data in a remote url:

[
  {
    "products": [
        {
          "productid": "01",
          "price": "01"
        },
        {
          "productid": "02",
          "price": "02"
        }
    ]
  }
]

I have also setup the corresponding codable structure. My questions is what would be the correct way to retrieve this data using the latest techniques for swift 4.

I am seeing various ways such as:

  • DataManager.getJSONFromURL ...
  • let jsonData = try Data(contentsOf: URL ...
  • let task = URLSession.shared.dataTask(with: url) ...
  • try JSONSerialization.data...

I would like to know which is the correct (latest) format for retrieving json data using swift 4 from a remote URL. Thank you.

like image 879
Robert Smith Avatar asked Jan 25 '18 19:01

Robert Smith


1 Answers

I found the answer to my question.

Apple announced Swift 4 as part of Xcode 9 at WWDC 2017. It brings some really nice improvements to existing Swift 3 features as well as stability. The latest ways of working with REST API in Swift 4 is using URLSession and JSONDecoder. The later was introduced with Swift 4.

In Swift 3, most of developers used third party frameworks such as SwiftyJson and Alamofire in order to work with REST APIs. The reason for this, most of the time, was that parsing JSON using Swift was very tedious. More precisely - you had to set up initializer in your Model, had to do loops to assign values in your controller, had to typecast values and so on. You could always copy/paste your code, but still it was overwhelming. With Swift 4 all you will need to do is to write just a single line to decode and parse JSON.

URLSession and JSONDecoder are all you need in Swift 4 for retrieving json data from a remote url.

For more information and an example, you can check this site:

URLSession and JSONDecoder in Swift 4

like image 83
Robert Smith Avatar answered Oct 17 '22 05:10

Robert Smith