Created
March 15, 2017 11:14
-
-
Save desmondmc/db065e3d16a0de77e997a482b127c1fd to your computer and use it in GitHub Desktop.
No Dependencies Swift Router
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 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