Skip to content

Instantly share code, notes, and snippets.

@desmondmc
Created March 15, 2017 11:14
Show Gist options
  • Save desmondmc/db065e3d16a0de77e997a482b127c1fd to your computer and use it in GitHub Desktop.
Save desmondmc/db065e3d16a0de77e997a482b127c1fd to your computer and use it in GitHub Desktop.
No Dependencies Swift Router
import Foundation
public protocol RequestConvertible {
var asRequest: NSMutableURLRequest { get }
}
enum NoDepsRouter: RequestConvertible {
case thing(id: String)
case postThings(id: String)
var host: String {
return "google.com"
}
var path: String {
switch self {
case .thing(let id):
return "/" + id
case .postThings(let id):
return "/things/" + id
}
}
var method: Method {
switch self {
case .thing: return .get
case .postThings: return .post
}
}
var params: Any? {
switch self {
case .thing:
return nil
case .postThings(let id):
return ["id": id,
"name":"blah"]
}
}
var query: [URLQueryItem]? {
return [URLQueryItem(name:"$filter", value: "1")]
}
var asRequest: NSMutableURLRequest {
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = query
guard let URL = urlComponents.url else {
fatalError("Couldn't build URL from components. Are you sure you're not missing a '/' at the start of the path value?")
}
let mutableURLRequest = NSMutableURLRequest(url: URL)
mutableURLRequest.httpMethod = method.rawValue
mutableURLRequest.setValue("Custom User-Agent", forHTTPHeaderField: "User-Agent")
if let params = params {
mutableURLRequest.encode(with: params)
}
return mutableURLRequest
}
}
private extension NSMutableURLRequest {
func encode(with jsonDictionary: Any) {
do {
let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: [])
self.setValue("application/json", forHTTPHeaderField: "Content-Type")
self.httpBody = data
} catch let error as NSError {
fatalError("Failed to encode JSON: \(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment