Skip to content

Instantly share code, notes, and snippets.

@psobko
Created March 5, 2018 09:52
Show Gist options
  • Save psobko/738858691e3da29548ef7b3df5f7c847 to your computer and use it in GitHub Desktop.
Save psobko/738858691e3da29548ef7b3df5f7c847 to your computer and use it in GitHub Desktop.
import Foundation
typealias PSHTTPClientResponseHandler = (Any?, URLResponse?, Error?) -> ()
class PSHTTPClient: NSObject {
private let shouldLog = false
private let shouldLogVerbose = true
private let session = URLSession.shared
public var baseURL:String = ""
public var headerFields:[String:String]
public var userAgent: String {
get {
return headerFields["User-Agent"] ?? ""
}
set(newUserAgent) {
headerFields["User-Agent"] = newUserAgent
}
}
override init() {
self.headerFields = ["User-Agent":"\(Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? "") 1.0"]
super.init()
}
convenience init(baseURL:String) {
self.init()
self.baseURL = baseURL
}
func getJSON(path: String, completionHandler: @escaping (PSHTTPClientResponseHandler)) {
let url = URL(string:"\(baseURL)\(path)")!
var request = URLRequest(url:url)
request.httpMethod = "GET"
for headerKey in headerFields.keys {
request.addValue(headerFields[headerKey]!, forHTTPHeaderField: headerKey)
}
performRequest(request: request) { (data: Any, response: URLResponse?, error: Error?) in
completionHandler(data, response, error)
}
}
}
// MARK: - Private
private extension PSHTTPClient {
func performRequest(request: URLRequest, completionHandler: @escaping (PSHTTPClientResponseHandler)) {
logRequest(request: request)
let startDate = Date()
session.dataTask(with: request as URLRequest) {
(data: Data?, response: URLResponse?, error: Error?) in
self.logResponse(response: response, startDate:startDate)
guard let d = data else { completionHandler(nil, response, error); return }
do {
let json = try JSONSerialization.jsonObject(with: d, options: .allowFragments)
completionHandler(json, response, error)
} catch let e as NSError {
completionHandler(nil, response, e)
}
}.resume()
}
}
// MARK: - Logging
extension PSHTTPClient {
func logRequest(request: URLRequest) {
if shouldLogVerbose {
print("""
[PSHTTPClient Request]
requestURL: \(request.url!)
httpMethod: \(request.httpMethod ?? "unknown")
headers: \(request.allHTTPHeaderFields ?? [:])
cachePolicy: \(request.cachePolicy)
timeout (s): \(request.timeoutInterval)
allowCell: \(request.allowsCellularAccess)
cookies: \(request.httpShouldHandleCookies)
pipelining: \(request.httpShouldUsePipelining)
[/Request]
""")
} else if shouldLog {
print("\(request.httpMethod!):'\(request.url!)")
}
}
func logResponse(response: URLResponse?, startDate: Date) {
if shouldLogVerbose {
if let response = response as? HTTPURLResponse {
print("""
[PSHTTPClient Response ---]
url: \(String(describing: response.url))
statusCode: \(response.statusCode)
headers: \(response.allHeaderFields)
mimeType: \(String(describing: response.mimeType))
duration: \(String(format: "%0.4fs", Date().timeIntervalSince(startDate)))
[/Response]
""")
}
} else if shouldLog {
if let response = response as? HTTPURLResponse {
print("Response \(response.statusCode):\(response.url!) \(String(format: "(%0.4fs))", Date().timeIntervalSince(startDate)))")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment