Created
November 16, 2017 00:57
-
-
Save mayoralito/edd0dc1d8f2595130e3ad64b1829782c to your computer and use it in GitHub Desktop.
Basic usage of Router for Network calls
This file contains 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
// Swift 3 | |
// Alamofire 4 | |
enum Router: URLRequestConvertible { | |
case updateUser(userId: Int, body:[String:Any]) | |
var method: HTTPMethod { | |
switch self { | |
case . updateUser(_,_): | |
return .put | |
} | |
} | |
var path: String { | |
switch self { | |
case . updateUser(let userId,_): | |
return "/users/\(userId)" | |
} | |
} | |
var parameters: [String: Any]? { | |
switch self { | |
case . updateUser(_, let body): | |
return body | |
} | |
} | |
var encoding:ParameterEncoding { | |
switch self { | |
case . updateUser(_,_): | |
// This will set HTTP multipart request | |
return URLEncoding(destination: .httpBody) | |
} | |
} | |
func asURLRequest() throws -> URLRequest { | |
// Do more here... | |
return try self.encoding.encode(request, with: self.parameters) | |
} | |
} | |
/// | |
// # How to use it. | |
let params: [String: Any]? | |
let manager = SessionManager(configuration: URLSessionConfiguration.default) | |
manager.request(Router.updateUser(userId: 1, body: params)) | |
.responseJSON() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment