Created
April 13, 2016 07:03
-
-
Save ivan3bx/96fba49f5d405cb99b680d12f10b8b3d to your computer and use it in GitHub Desktop.
Using enums to define an API router where query params are defined in a trailing closure (updated for latest Swift)
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
// http://eliasbagley.github.io/json/api/alamofire/2015/09/25/making-network-requests-with-alamofire.html | |
enum APIRouter: URLRequestConvertible | |
{ | |
static let BASE_URL = "http://foo" | |
static let API_KEY = "1231254" | |
case User(Int, closure: () -> [String:AnyObject]) | |
case Likes(Int, Int) | |
var URLRequest: NSMutableURLRequest | |
{ | |
var path:String! | |
var parameters:[String:AnyObject] | |
switch(self) { | |
case .User (let page, let closure): | |
parameters = closure() | |
path = "/user/\(page)" | |
case .Likes(let id, let commentsPage): | |
parameters = ["commentsPage":commentsPage] | |
path = "/likes/\(id)/user" | |
} | |
let URL = NSURL(string: APIRouter.BASE_URL) | |
let URLRequest = NSURLRequest(URL:URL!.URLByAppendingPathComponent(path)) | |
let encoding = Alamofire.ParameterEncoding.URL | |
return encoding.encode(URLRequest, parameters: parameters).0 | |
} | |
} | |
// Example | |
let x = APIRouter.User(4) { ["this":"that"] } | |
print(x.URLRequest) // -> URL: http://foo/user/4?this=that | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment