Skip to content

Instantly share code, notes, and snippets.

@avdyushin
Created January 25, 2016 12:17
Show Gist options
  • Save avdyushin/0b88d2df0fd6ef55dbb9 to your computer and use it in GitHub Desktop.
Save avdyushin/0b88d2df0fd6ef55dbb9 to your computer and use it in GitHub Desktop.
Demo HTTP client for RESTful services in Swift 2.0
import Foundation
class HttpClient: NSObject {
let logging = true
let session = NSURLSession.sharedSession()
func makeRequest(request: NSURLRequest, completionHandler: (NSDictionary?, NSURLResponse?, NSError?) -> Void) {
logRequest(request)
let startTime = NSDate()
session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
self.logResponse(response, timeInterval: NSDate().timeIntervalSinceDate(startTime))
guard let d = data else { completionHandler(nil, response, error); return }
do {
let json = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
completionHandler(json, response, error)
} catch let e as NSError {
completionHandler(nil, response, e)
}
}.resume()
}
func getJSON(path: String, completionHandler: (NSDictionary?, NSURLResponse?, NSError?) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
request.HTTPMethod = "GET"
request.addValue("HttpClient 1.0", forHTTPHeaderField: "User-Agent")
makeRequest(request) { (data: NSDictionary?, response: NSURLResponse?, error: NSError?) -> Void in
completionHandler(data, response, error)
}
}
func logRequest(request: NSURLRequest) {
if logging {
print("\(request.HTTPMethod!) '\(request.URL!)'")
}
}
func logResponse(response: NSURLResponse?, timeInterval: NSTimeInterval) {
if logging {
if let response = response as? NSHTTPURLResponse {
print("\(response.statusCode) '\(response.URL!)' \(NSString(format: "[%0.4f s]", timeInterval))")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment