Skip to content
Pascal Pfiffner edited this page Sep 15, 2016 · 1 revision

Here's an extension that can be used with Alamofire (tested with version 3.0). You will need to call authorize() yourself and coordinate your Alamofire calls accordingly. If you can, update to OAuth2 version 3.0 and use Alamofire v4; it's much easier!

import Alamofire

extension OAuth2 {
    public func request(
        method: Alamofire.Method,
        _ URLString: URLStringConvertible,
        parameters: [String: AnyObject]? = nil,
        encoding: Alamofire.ParameterEncoding = .URL,
        headers: [String: String]? = nil)
        -> Alamofire.Request
    {
        
        var hdrs = headers ?? [:]
        if let token = accessToken {
            hdrs["Authorization"] = "Bearer \(token)"
        }
        return Alamofire.request(
            method,
            URLString,
            parameters: parameters,
            encoding: encoding,
            headers: hdrs)
    }
}

You can now use the handle to your OAuth2 instance instead of using Alamofire directly to make requests that are signed. Of course this will only work once you have an access token. You can use hasUnexpiredAccessToken() to check for one or just always call authorize() first; it will call your callback immediately if you have a token.

oauth2.request(.GET, "http://httpbin.org/get")
Clone this wiki locally