Skip to content

Instantly share code, notes, and snippets.

@Pasanpr
Created April 12, 2017 17:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pasanpr/7680402d3c7026912aa94d46468696d0 to your computer and use it in GitHub Desktop.
Save Pasanpr/7680402d3c7026912aa94d46468696d0 to your computer and use it in GitHub Desktop.
import Foundation
class JSONDownloader {
let session: URLSession
init(configuration: URLSessionConfiguration) {
self.session = URLSession(configuration: configuration)
}
convenience init() {
self.init(configuration: .default)
}
typealias JSON = [String: AnyObject]
typealias JSONTaskCompletionHandler = (JSON?, ItunesError?) -> Void
func jsonTask(with request: URLRequest, completionHandler completion: @escaping JSONTaskCompletionHandler) -> URLSessionDataTask {
let task = session.dataTask(with: request) { data, response, error in
guard let httpResponse = response as? HTTPURLResponse else {
completion(nil, .requestFailed)
return
}
if httpResponse.statusCode == 200 {
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject]
completion(json, nil)
} catch {
completion(nil, .jsonConversionFailure)
}
} else {
completion(nil, .invalidData)
}
} else {
completion(nil, .responseUnsuccessful)
}
}
return task
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment