Skip to content

Instantly share code, notes, and snippets.

@oliverfoggin
Created June 9, 2016 14:59
Show Gist options
  • Save oliverfoggin/119baa971678f8c04e293874b2d4c5ab to your computer and use it in GitHub Desktop.
Save oliverfoggin/119baa971678f8c04e293874b2d4c5ab to your computer and use it in GitHub Desktop.
enum Router: URLRequestConvertible {
static let baseURLString = "http://someURL.co.uk"
static var OAuthToken: String? {
didSet {
// save token to keychain
}
}
case AuthCheck
case Login(email: String, deviceID: String, firstName: String?, lastName: String?)
case Search(query: String)
case SearchPage(url: NSURL)
case TeamDetails(url: NSURL)
case Projects()
var method: Alamofire.Method {
switch self {
case .Search, .SearchPage, .AuthCheck, .CampaignDetails, Causes:
return .GET
case .Login:
return .POST
}
}
var path: String {
switch self {
case .Search:
return "/api/search"
case .Login:
return "/api/auth"
case .AuthCheck:
return "/api/auth/check"
case .Teams:
return "/api/teams"
default:
return ""
}
}
var URL: NSURL {
var URL: NSURL!
switch self {
case .SearchPage(let url):
URL = url
case .CampaignDetails(let url):
URL = url
default:
URL = NSURL(string: Router.baseURLString)!
}
return URL
}
var URLRequest: NSMutableURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let token = Router.OAuthToken {
mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
} else {
if let token = KeychainToken() {
mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
switch self {
case .Search(let query):
return Alamofire.ParameterEncoding.URLEncodedInURL.encode(mutableURLRequest, parameters: ["q" : query]).0
case .Login(let email, let id, let firstName, let lastName):
var parameters = ["email" : email,
"id" : id]
parameters["first_name"] = firstName
parameters["last_name"] = lastName
return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
default:
return mutableURLRequest
}
}
}
To run a request I don't need to know any urls or remember parameters etc... They are all embedded into the Router...
For instance to run a search query...
Alamofire.request(Router.Search("some query string"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment