5
votes

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.

3
have you tried them all?bearacuda13
Thank you for your comment. No I have not. I am just adding json to my app and would like to make sure I am using the latest method for swift 4. I do understand the codable option is new and would like to use that with the call to retrieve the json data. Thank you.Robert Smith

3 Answers

9
votes

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

0
votes
func getRequestWithUrl(url : String ,onCompletionHandler : @escaping ([String : Any]?) -> Void){

        let headers : HTTPHeaders = [
            "X-Api-Key": "EPE67704498C76B16CF29B956B2A2E91",
            "Accept": "application/json",

            ]
        Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            switch response.result {
            case .success:
                onCompletionHandler(response.result.value as? [String : Any])
                break
            case .failure(_):
                onCompletionHandler(nil)
            }
        }
}
0
votes

we have an API which allows us to create a new board with a title “New York Highlights”. For this, using Alamofire the code is very easy:

AF.request("https://api.mywebserver.com/v1/board", method: .get, parameters: ["title": "New York Highlights"])
    .validate(statusCode: 200..<300)
    .responseDecodable { (response: DataResponse) in
        switch response.result {
        case .success(let board):
            print("Created board title is \(board.title)") // New York Highlights
        case .failure(let error):
            print("Board creation failed with error: \(error.localizedDescription)")
        }
}

For Alamofire you need to install framework for more detail read this document

Doing exactly the same with the URLSession API requires a bit more of work.

enum Error: Swift.Error {
    case requestFailed
}

// Build up the URL
var components = URLComponents(string: "https://api.mywebserver.com/v1/board")!
components.queryItems = ["title": "New York Highlights"].map { (key, value) in
    URLQueryItem(name: key, value: value)
}

// Generate and execute the request
let request = try! URLRequest(url: components.url!, method: .get)
URLSession.shared.dataTask(with: request) { (data, response, error) in
    do {
        guard let data = data,
            let response = response as? HTTPURLResponse, (200 ..< 300) ~= response.statusCode,
            error == nil else {
            // Data was nil, validation failed or an error occurred.
            throw error ?? Error.requestFailed
        }
        let board = try JSONDecoder().decode(Board.self, from: data)
        print("Created board title is \(board.title)") // New York Highlights
    } catch {
        print("Board creation failed with error: \(error.localizedDescription)")
    }
}

credit