Swift 2.0: best practice for communicating with REST API with JSON

I started migrating to Swift and just realized that most of the Sample Code no longer works in Swift 2.0, and it’s very difficult to get in as newbies.

So what is the best practice for communicating with the REST API in Swift 2.0 using the Swift methods from the standard libraries?

Can someone provide Swift 2.0 Code for the following scenario?

  • GET JSON data from service
  • JSON parsing (so it can be used in Swift)
  • Send a POST request with JSON encoded data.

Please provide a solution without Framework. Hope this helps all other people trying to get tutorials from the internet to work on Swift 2.0.

+4
source share
1 answer

I am starting too, and I cannot say that what I am doing is the best practice, but here is how I processed the GET request using NSURLSession and closing .

First, I defined a NetworkOperation class that will handle NSURLSession. It has the following attributes:

lazy var config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config)
let queryURL: NSURL

In the initializer, I set queryURL. Configuration and vars sessions lazy, because I want them to be initialized only when using my network operation.

Then I have a method that executes a GET request and retrieves JSON. This method takes closure as parameters. This closure will be provided by the caller and allows me to map the response to my data request to the calling context.

func downloadJSONFromURl(completion: ([String:AnyObject]?) -> ()) {
    let request = NSURLRequest(URL: queryURL)

    let dataTask = session.dataTaskWithRequest(request) {
        (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in

        // 1: Check HTTP Response for successful GET request
        guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
        else {
            print("error: not a valid http response")
            return
        }

        switch (httpResponse.statusCode) {
        case 200:
            // 2: Create JSON object with data
            do {
                let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments)
                    as? [String:AnyObject]

                // 3: Pass the json back to the completion handler
                completion(jsonDictionary)
            } catch {
                print("error parsing json data")
            }
        default:
            print("GET request got response \(httpResponse.statusCode)")
        }
    }
    dataTask.resume()
}

, , JSON [String:AnyObject] catch try.

completion, JSON, Swift.

. , , , JSON : {title: "Some book", author:"J. Doe"}

if let title = json["author"] as? String, author = json["author"] as? String {
    let book = Book(title: title, author: author)
    serviceCompletion(book)
}

, JSON , . github. Treehouse.

, .

+3

All Articles