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
guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
else {
print("error: not a valid http response")
return
}
switch (httpResponse.statusCode) {
case 200:
do {
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments)
as? [String:AnyObject]
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.
, .