ios html Alamofire


Alamofire: Elegant Networking in Swift

Build Status

Alamofire is an HTTP networking library written in Swift, from the creator of AFNetworking.


  • Chainable Request / Response methods
  • URL / JSON / plist Parameter Encoding
  • Upload File / Data / Stream
  • Download using Request or Resume data
  • Authentication with NSURLCredential
  • HTTP Response Validation
  • Progress Closure & NSProgress
  • cURL Debug Output
  • Comprehensive Unit Test Coverage
  • Complete Documentation


  • iOS 7.0+ / Mac OS X 10.9+
  • Xcode 6.3


  • If you need help, use Stack Overflow. (Tag ‘alamofire’)
  • If you’d like to ask a general question, use Stack Overflow.
  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.


Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks.

To use Alamofire with a project targeting iOS 7, you must include the Alamofire.swift source file directly in your project. See the ‘Source File’ section for instructions.


CocoaPods is a dependency manager for Cocoa projects.

CocoaPods 0.36 adds supports for Swift and embedded frameworks. You can install it with the following command:

$ gem install cocoapods

To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

source ''
platform :ios, '8.0'

pod 'Alamofire', '~> 1.2'

Then, run the following command:

$ pod install


Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

github "Alamofire/Alamofire" >= 1.2


If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

Embedded Framework

  • Add Alamofire as a submodule by opening the Terminal, cd-ing into your top-level project directory, and entering the following command:
$ git submodule add
  • Open the Alamofire folder, and drag Alamofire.xcodeproj into the file navigator of your app project.
  • In Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the “Targets” heading in the sidebar.
  • Ensure that the deployment target of Alamofire.framework matches that of the application target.
  • In the tab bar at the top of that window, open the “Build Phases” panel.
  • Expand the “Target Dependencies” group, and add Alamofire.framework.
  • Click on the + button at the top left of the panel and select “New Copy Files Phase”. Rename this new phase to “Copy Frameworks”, set the “Destination” to “Frameworks”, and addAlamofire.framework.

Source File

For application targets that do not support embedded frameworks, such as iOS 7, Alamofire can be integrated by adding the Alamofire.swift source file directly into your project. Note that any calling conventions described in the ‘Usage’ section with the Alamofire prefix would instead omit it (for example, Alamofire.request becomes request), since this functionality is incorporated into the top-level namespace.


Making a Request

import Alamofire

Alamofire.request(.GET, "")

Response Handling

Alamofire.request(.GET, "", parameters: ["foo": "bar"])
         .response { (request, response, data, error) in

Networking in Alamofire is done asynchronously. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are very good reasons for doing it this way.

Rather than blocking execution to wait for a response from the server, a callback is specified to handle the response once it’s received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler.

Response Serialization

Built-in Response Methods

  • response()
  • responseString(encoding: NSStringEncoding)
  • responseJSON(options: NSJSONReadingOptions)
  • responsePropertyList(options: NSPropertyListReadOptions)

Response String Handler

Alamofire.request(.GET, "")
         .responseString { (_, _, string, _) in

Response JSON Handler

Alamofire.request(.GET, "")
         .responseJSON { (_, _, JSON, _) in

Chained Response Handlers

Response handlers can even be chained:

Alamofire.request(.GET, "")
         .responseString { (_, _, string, _) in
         .responseJSON { (_, _, JSON, _) in

HTTP Methods

Alamofire.Method lists the HTTP methods defined in RFC 7231 §4.3:

public enum Method: String {
    case OPTIONS = "OPTIONS"
    case GET = "GET"
    case HEAD = "HEAD"
    case POST = "POST"
    case PUT = "PUT"
    case PATCH = "PATCH"
    case DELETE = "DELETE"
    case TRACE = "TRACE"
    case CONNECT = "CONNECT"

These values can be passed as the first argument of the Alamofire.request method:

Alamofire.request(.POST, "")

Alamofire.request(.PUT, "")

Alamofire.request(.DELETE, "")


GET Request With URL-Encoded Parameters

Alamofire.request(.GET, "", parameters: ["foo": "bar"])

POST Request With URL-Encoded Parameters

let parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3

Alamofire.request(.POST, "", parameters: parameters)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3

Parameter Encoding

Parameters can also be encoded as JSON, Property List, or any custom format, using theParameterEncoding enum:

enum ParameterEncoding {
    case URL
    case JSON
    case PropertyList(format: NSPropertyListFormat,
                      options: NSPropertyListWriteOptions)

    func encode(request: NSURLRequest,
                parameters: [String: AnyObject]?) ->
                    (NSURLRequest, NSError?)
    { ... }
  • URL: A query string to be set as or appended to any existing URL query for GET, HEAD, andDELETE requests, or set as the body for requests with any other HTTP method. The Content-Type HTTP header field of an encoded request with HTTP body is set to application/x-www-form-urlencoded. Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz).
  • JSON: Uses NSJSONSerialization to create a JSON representation of the parameters object, which is set as the body of the request. The Content-Type HTTP header field of an encoded request is set to application/json.
  • PropertyList: Uses NSPropertyListSerialization to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The Content-Type HTTP header field of an encoded request is set toapplication/x-plist.
  • Custom: Uses the associated closure value to construct a new request given an existing request and parameters.

Manual Parameter Encoding of an NSURLRequest

let URL = NSURL(string: "")!
var request = NSURLRequest(URL: URL)

let parameters = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters: parameters)

POST Request with JSON-encoded Parameters

let parameters = [
    "foo": [1,2,3],
    "bar": [
        "baz": "qux"

Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON)
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}


Caching is handled on the system framework level by NSURLCache.


Supported Upload Types

  • File
  • Data
  • Stream

Uploading a File

let fileURL = NSBundle.mainBundle()
                                      withExtension: "png")

Alamofire.upload(.POST, "", file: fileURL)

Uploading w/Progress

Alamofire.upload(.POST, "", file: fileURL)
         .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
         .responseJSON { (request, response, JSON, error) in


Supported Download Types

  • Request
  • Resume Data

Downloading a File, "", destination: { (temporaryURL, response) in
    if let directoryURL = NSFileManager.defaultManager()
                                            inDomains: .UserDomainMask)[0]
                          as? NSURL {
        let pathComponent = response.suggestedFilename

        return directoryURL.URLByAppendingPathComponent(pathComponent!)

    return temporaryURL

Using the Default Download Destination

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask), "", destination: destination)

Downloading a File w/Progress, "", destination: destination)
         .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
         .response { (request, response, _, error) in


Authentication is handled on the system framework level by NSURLCredential andNSURLAuthenticationChallenge.

Supported Authentication Schemes

HTTP Basic Authentication

let user = "user"
let password = "password"

Alamofire.request(.GET, "\(user)/\(password)")
         .authenticate(user: user, password: password)
         .response {(request, response, _, error) in

Authentication with NSURLCredential

let user = "user"
let password = "password"

let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)

Alamofire.request(.GET, "\(user)/\(password)")
         .authenticate(usingCredential: credential)
         .response {(request, response, _, error) in


By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

Manual Validation

Alamofire.request(.GET, "", parameters: ["foo": "bar"])
         .validate(statusCode: 200..<300)
         .validate(contentType: ["application/json"])
         .response { (_, _, _, error) in

Automatic Validation

Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request(.GET, "", parameters: ["foo": "bar"])
         .response { (_, _, _, error) in


let request = Alamofire.request(.GET, "")

// GET (200)


let request = Alamofire.request(.GET, "", parameters: ["foo": "bar"])


Output (cURL)

$ curl -i \
    -H "User-Agent: Alamofire" \
    -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
    -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \

Advanced Usage

Alamofire is built on NSURLSession and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack.

Recommended Reading


Top-level convenience methods like Alamofire.request use a shared instance of Alamofire.Manager, which is configured with the default NSURLSessionConfiguration.

As such, the following two statements are equivalent:

Alamofire.request(.GET, "")
let manager = Alamofire.Manager.sharedInstance
manager.request(NSURLRequest(URL: NSURL(string: "")))

Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers (HTTPAdditionalHeaders) or timeout interval (timeoutIntervalForRequest).

Creating a Manager with Default Configuration

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let manager = Alamofire.Manager(configuration: configuration)

Creating a Manager with Background Configuration

let configuration = NSURLSessionConfiguration.backgroundSessionConfiguration("")
let manager = Alamofire.Manager(configuration: configuration)

Creating a Manager with Ephemeral Configuration

let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let manager = Alamofire.Manager(configuration: configuration)

Modifying Session Configuration

var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

let manager = Alamofire.Manager(configuration: configuration)

This is not recommended for Authorization or Content-Type headers. Instead, useURLRequestConvertible and ParameterEncoding, respectively.


The result of a request, upload, or download method is an instance of Alamofire.Request. A request is always created using a constructor method from an owning manager, and never initialized directly.

Methods like authenticate, validate, and response return the caller in order to facilitate chaining.

Requests can be suspended, resumed, and cancelled:

  • suspend(): Suspends the underlying task and dispatch queue
  • resume(): Resumes the underlying task and dispatch queue. If the owning manager does not have startRequestsImmediately set to true, the request must call resume() in order to start.
  • cancel(): Cancels the underlying task, producing an error that is passed to any registered response handlers.

Response Serialization

Creating a Custom Response Serializer

Alamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on Alamofire.Request.

For example, here’s how a response handler using Ono might be implemented:

extension Request {
    class func XMLResponseSerializer() -> Serializer {
        return { (request, response, data) in
            if data == nil {
                return (nil, nil)

            var XMLSerializationError: NSError?
            let XML = ONOXMLDocument(data: data, &XMLSerializationError)

            return (XML, XMLSerializationError)

    func responseXMLDocument(completionHandler: (NSURLRequest, NSHTTPURLResponse?, ONOXMLDocument?, NSError?) -> Void) -> Self {
        return response(serializer: Request.XMLResponseSerializer(), completionHandler: { (request, response, XML, error) in
            completionHandler(request, response, XML as? ONOXMLDocument, error)

Generic Response Object Serialization

Generics can be used to provide automatic, type-safe response object serialization.

@objc public protocol ResponseObjectSerializable {
    init?(response: NSHTTPURLResponse, representation: AnyObject)

extension Alamofire.Request {
    public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                return (T(response: response!, representation: JSON!), nil)
            } else {
                return (nil, serializationError)

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
            completionHandler(request, response, object as? T, error)
final class User: ResponseObjectSerializable {
    let username: String
    let name: String

    required init?(response: NSHTTPURLResponse, representation: AnyObject) {
        self.username = response.URL!.lastPathComponent = representation.valueForKeyPath("name") as String
Alamofire.request(.GET, "")
         .responseObject { (_, _, user: User?, _) in

The same approach can also be used to handle endpoints that return a representation of a collection of objects:

@objc public protocol ResponseCollectionSerializable {
    class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]

extension Alamofire.Request {
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                return (T.collection(response: response!, representation: JSON!), nil)
            } else {
                return (nil, serializationError)

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
            completionHandler(request, response, object as? [T], error)


Types adopting the URLStringConvertible protocol can be used to construct URL strings, which are then used to construct URL requests. NSString, NSURL, NSURLComponents, and NSURLRequestconform to URLStringConvertible by default, allowing any of them to be passed as URLStringparameters to the request, upload, and download methods:

let string = NSString(string: "")
Alamofire.request(.POST, string)

let URL = NSURL(string: string)!
Alamofire.request(.POST, URL)

let URLRequest = NSURLRequest(URL: URL)
Alamofire.request(.POST, URLRequest) // overrides `HTTPMethod` of `URLRequest`

let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: true)
Alamofire.request(.POST, URLComponents)

Applications interacting with web applications in a significant manner are encouraged to have custom types conform to URLStringConvertible as a convenient way to map domain-specific models to server resources.

Type-Safe Routing

extension User: URLStringConvertible {
    static let baseURLString = ""

    var URLString: String {
        return User.baseURLString + "/users/\(username)/"
let user = User(username: "mattt")
Alamofire.request(.GET, user) //


Types adopting the URLRequestConvertible protocol can be used to construct URL requests.NSURLRequest conforms to URLRequestConvertible by default, allowing it to be passed into request,upload, and download methods directly (this is the recommended way to specify custom HTTP header fields or HTTP body for individual requests):

let URL = NSURL(string: "")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["foo": "bar"]
var JSONSerializationError: NSError? = nil
mutableURLRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &JSONSerializationError)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")


Applications interacting with web applications in a significant manner are encouraged to have custom types conform to URLRequestConvertible as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state.

API Parameter Abstraction

enum Router: URLRequestConvertible {
    static let baseURLString = ""
    static let perPage = 50

    case Search(query: String, page: Int)

    // MARK: URLRequestConvertible

    var URLRequest: NSURLRequest {
        let (path: String, parameters: [String: AnyObject]?) = {
            switch self {
            case .Search(let query, let page) where page > 1:
                return ("/search", ["q": query, "offset": Router.perPage * page])
            case .Search(let query, _):
                return ("/search", ["q": query])

        let URL = NSURL(string: Router.baseURLString)!
        let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(path))
        let encoding = Alamofire.ParameterEncoding.URL

        return encoding.encode(URLRequest, parameters: parameters).0
Alamofire.request(Router.Search(query: "foo bar", page: 1)) // ?q=foo+bar&offset=50

CRUD & Authorization

enum Router: URLRequestConvertible {
    static let baseURLString = ""
    static var OAuthToken: String?

    case CreateUser([String: AnyObject])
    case ReadUser(String)
    case UpdateUser(String, [String: AnyObject])
    case DestroyUser(String)

    var method: Alamofire.Method {
        switch self {
        case .CreateUser:
            return .POST
        case .ReadUser:
            return .GET
        case .UpdateUser:
            return .PUT
        case .DestroyUser:
            return .DELETE

    var path: String {
        switch self {
        case .CreateUser:
            return "/users"
        case .ReadUser(let username):
            return "/users/\(username)"
        case .UpdateUser(let username, _):
            return "/users/\(username)"
        case .DestroyUser(let username):
            return "/users/\(username)"

    // MARK: URLRequestConvertible

    var URLRequest: NSURLRequest {
        let URL = NSURL(string: Router.baseURLString)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
        mutableURLRequest.HTTPMethod = method.rawValue

        if let token = Router.OAuthToken {
            mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

        switch self {
        case .CreateUser(let parameters):
            return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
        case .UpdateUser(_, let parameters):
            return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
            return mutableURLRequest
Alamofire.request(Router.ReadUser("mattt")) // GET /users/mattt


When should I use Alamofire?

If you’re starting a new project in Swift, and want to take full advantage of its conventions and language features, Alamofire is a great choice. Although not as fully-featured as AFNetworking, Alamofire is much nicer to work with, and should satisfy the vast majority of networking use cases.

It’s important to note that two libraries aren’t mutually exclusive: AFNetworking and Alamofire can peacefully exist in the same code base.

When should I use AFNetworking?

AFNetworking remains the premiere networking library available for OS X and iOS, and can easily be used in Swift, just like any other Objective-C code. AFNetworking is stable and reliable, and isn’t going anywhere.

Use AFNetworking for any of the following:

  • UIKit extensions, such as asynchronously loading images to UIImageView
  • TLS verification, using AFSecurityManager
  • Situations requiring NSOperation or NSURLConnection, using AFURLConnectionOperation
  • Network reachability monitoring, using AFNetworkReachabilityManager
  • Multipart HTTP request construction, using AFHTTPRequestSerializer

What’s the origin of the name Alamofire?

Alamofire is named after the Alamo Fire flower, a hybrid variant of the Bluebonnet, the official state flower of Texas.


Follow AFNetworking on Twitter (@AFNetworking)



Alamofire is released under the MIT license. See LICENSE for details.

21 Responses so far.

  1. kilogram says:
    I was recommended this blog by my cousin. I am not sure whether this post is written by him as nobody
    else know such detailed about my trouble. You are incredible!
  2. história says:
    Thanks for every other informative blog.
    The place else may I am getting that kind of
    information written in such a perfect way? I have
    a project that I’m simply now working on, and I’ve been on the look out
    for such info.
  3. ответы says:
    A fascinating discussion is worth comment. I do believe that you
    should publish more about this issue, it may not be a taboo subject but typically folks don’t discuss such
    issues. To the next! Kind regards!!
  4. sydney says:
    Does your blog have a contact page? I’m having problems locating
    it but, I’d like to send you an email. I’ve got some ideas for your
    blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing
    it grow over time.
  5. removalist says:
    Hello it’s me, I am also visiting this web site on a regular basis, this web page is truly pleasant and the people are genuinely sharing nice thoughts.|
  6. Website says:
    After looking over a number of the blog posts on your site, I seriously appreciate your way of blogging. I added it to my bookmark website list and will be checking back in the near future. Please check out my website as well and tell me your opinion.|
  7. quest bars says:
    I blog often and I seriously thank you for your information. The article has
    really peaked my interest. I will bookmark your blog and keep checking for
    new details about once per week. I opted in for your
    Feed too.
  8. quest bars says:
    Thank you, I have recently been looking for information approximately this topic for a
    while and yours is the best I have discovered so far.
    However, what in regards to the conclusion? Are you sure in regards to the supply?
  9. I know this web site offers quality based articles and extra data, is there any other site which gives these kinds of things in quality?
  10. I’m not sure exactly why but this weblog is loading incredibly slow for me.
    Is anyone else having this issue or is it a problem on my end?

    I’ll check back later and see if the problem still exists.

  11. We stumbled over here different web address and thought I should check
    things out. I like what I see so now i am following you.
    Look forward to exploring your web page yet again.
  12. Hello to every one, the contents present at this site are genuinely awesome for people
    knowledge, well, keep up the nice work fellows.
  13. At this time it seems like Drupal is the top blogging platform available right now.
    (from what I’ve read) Is that what you’re using on your blog?
  14. Thanks designed for sharing such a pleasant idea, paragraph is good, thats why i have read it completely
  15. My brother suggested I may like this blog. He used to be entirely right.
    This submit truly made my day. You can not imagine
    simply how so much time I had spent for this information! Thank you!
  16. My family every time say that I am wasting my
    time here at web, but I know I am getting experience daily by reading
    thes fastidious articles.
  17. Truly no matter if someone doesn’t know afterward its up
    to other viewers that they will help, so here it takes place.
  18. Hello, i think that i noticed you visited my web
    site thus i got here to return the favor?.I’m trying
    to in finding things to enhance my website!I assume
    its good enough to make use of some of your ideas!!
  19. Good post. I learn something totally new and challenging on blogs
    I stumbleupon everyday. It will always be helpful to read through content from other writers and
    use a little something from their websites.
  20. riley evans says:
    Say, you got a nice blog article.Really looking forward to read more. Awesome.