Skip to content

Instantly share code, notes, and snippets.

@leojkwan
Last active February 20, 2017 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leojkwan/bbdd49e51a8fb8bed6a9d4d927016826 to your computer and use it in GitHub Desktop.
Save leojkwan/bbdd49e51a8fb8bed6a9d4d927016826 to your computer and use it in GitHub Desktop.
Shared URLSession Networking Client
import UIKit
public typealias RequestResponse = (_ statusCode:Int, _ data:AnyObject?) -> Void
struct RequestManager {
static func makeHTTPSRequest(
_ token: String?,
postBody: AnyObject? = nil,
methodString:String,
urlString:String,
completion: @escaping (RequestResponse)) throws {
// Create a default session
// This provides a default session with default configs for caching, cookies, etc.
let session = URLSession.shared
// Create a request object
let url:URL = URL(string: urlString)!
let request = NSMutableURLRequest(url: url)
request.httpMethod = methodString
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
// Add access token if need
if let accessToken = token {
request.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
}
// Add request body for PUT and POST operations
if let postBody = postBody {
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postBody, options: [])
} catch {
print(error)
}
}
// Create a data task object
let task = session.dataTask(with: (request as URLRequest), completionHandler: {(data, response, error) in
guard let response = response as? HTTPURLResponse else {
debugPrint("response not http")
return
}
guard response.statusCode < 400 else {
if response.statusCode == 401 {
print("Status Code:\(response.statusCode), Not Authorized")
} else {
print("Status Code:\(response.statusCode), Error reaching resource, \(request.url)")
}
completion(response.statusCode, nil)
return
}
guard error == nil else {
completion(response.statusCode, nil)
print("Error connecting to server. Message: \(error?.localizedDescription)")
return
}
// Parse Data
if let data = data {
if let dataDict = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]) {
completion(response.statusCode, dataDict as AnyObject?)
} else {
completion(response.statusCode, data as AnyObject?)
}
} else {
// Successful request- no data, send status code
completion(response.statusCode, nil)
}
})
// Stark task
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment