Last active
January 25, 2017 02:54
-
-
Save chriswebb09/8e78e9e2a4a69feefea21452b7a6ea10 to your computer and use it in GitHub Desktop.
APIClients Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
typealias JSONData = [String:Any] | |
struct APIClient { | |
let session = URLSession.shared | |
func createRequest(url: URL) -> URLRequest { | |
return URLRequest(url: url) | |
} | |
func startTask(request: URLRequest, handler: @escaping (JSONData) -> ()) { | |
session.dataTask(with: request, completionHandler: { data, response, error in | |
guard let responseData = data else { return } | |
do { | |
let json = try JSONSerialization.jsonObject(with: responseData, options: []) as! JSONData | |
handler(json) | |
} catch { | |
print(error.localizedDescription) | |
} | |
}).resume() | |
} | |
func downloadImage(request: URLRequest, handler: @escaping (UIImage) -> ()) { | |
session.dataTask(with: request, completionHandler: { data, response, error in | |
guard let responseData = data else { return } | |
let image = UIImage(data: responseData)! | |
handler(image) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment