Skip to content

Instantly share code, notes, and snippets.

@ivan3bx
Created April 13, 2016 07:03
Show Gist options
  • Save ivan3bx/96fba49f5d405cb99b680d12f10b8b3d to your computer and use it in GitHub Desktop.
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)
// 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