Inherits from NSObject
Conforms to NSCoding
NSCopying
Declared in AFHTTPClient.h

Overview

AFHTTPClient captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations.

Automatic Content Parsing

Instances of AFHTTPClient may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in enqueueHTTPRequestOperationWithRequest:success:failure.

Subclassing Notes

In most cases, one should create an AFHTTPClient subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application.

Methods to Override

To change the behavior of all url request construction for an AFHTTPClient subclass, override requestWithMethod:path:parameters.

To change the behavior of all request operation construction for an AFHTTPClient subclass, override HTTPRequestOperationWithRequest:success:failure.

Default Headers

By default, AFHTTPClient sets the following HTTP headers:

  • Accept-Language: (comma-delimited preferred languages), en-us;q=0.8
  • User-Agent: (generated user agent)

You can override these HTTP headers or define new ones using setDefaultHeader:value:.

URL Construction Using Relative Paths

Both requestWithMethod:path:parameters: and multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock: construct URLs from the path relative to the baseURL, using NSURL +URLWithString:relativeToURL:. Below are a few examples of how baseURL and relative paths interact:

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]http://example.com/v1/"];  
[NSURL URLWithString:@"foo" relativeToURL:baseURL];                  // http://example.com/v1/foo
[NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL];          // http://example.com/v1/foo?bar=baz
[NSURL URLWithString:@"/foo" relativeToURL:baseURL];                 // http://example.com/foo
[NSURL URLWithString:@"foo/" relativeToURL:baseURL];                 // http://example.com/v1/foo
[NSURL URLWithString:@"/foo/" relativeToURL:baseURL];                // http://example.com/foo/
[NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/

Also important to note is that a trailing slash will be added to any baseURL without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.

NSCoding / NSCopying Conformance

AFHTTPClient conforms to the NSCoding and NSCopying protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however:

  • Archives and copies of HTTP clients will be initialized with an empty operation queue.
  • NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set.

Tasks

Accessing HTTP Client Properties

  •   baseURL

    The url used as the base for paths specified in methods such as getPath:parameters:success:failure

    property
  •   stringEncoding

    The string encoding used in constructing url requests. This is NSUTF8StringEncoding by default.

    property
  •   parameterEncoding

    The AFHTTPClientParameterEncoding value corresponding to how parameters are encoded into a request body. This is AFFormURLParameterEncoding by default.

    property
  •   operationQueue

    The operation queue which manages operations enqueued by the HTTP client.

    property
  •   networkReachabilityStatus

    The reachability status from the device to the current baseURL of the AFHTTPClient.

    property

Creating and Initializing HTTP Clients

Managing Reachability Status

Managing HTTP Operations

Managing HTTP Header Values

  • – defaultValueForHeader:

    Returns the value for the HTTP headers set in request objects created by the HTTP client.

  • – setDefaultHeader:value:

    Sets the value for the HTTP headers set in request objects made by the HTTP client. If nil, removes the existing value for that header.

  • – setAuthorizationHeaderWithUsername:password:

    Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.

  • – setAuthorizationHeaderWithToken:

    Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.

  • – clearAuthorizationHeader

    Clears any existing value for the “Authorization” HTTP header.

Creating Request Objects

Creating HTTP Operations

Managing Enqueued HTTP Operations

Batching HTTP Request Operations

Making HTTP Requests

Properties

baseURL

The url used as the base for paths specified in methods such as getPath:parameters:success:failure

@property (readonly, nonatomic) NSURL *baseURL

Discussion

The url used as the base for paths specified in methods such as getPath:parameters:success:failure

Declared In

AFHTTPClient.h

networkReachabilityStatus

The reachability status from the device to the current baseURL of the AFHTTPClient.

@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus

Discussion

The reachability status from the device to the current baseURL of the AFHTTPClient.

Warning: This property requires the SystemConfiguration framework. Add it in the active target’s “Link Binary With Library” build phase, and add #import <SystemConfiguration/SystemConfiguration.h> to the header prefix of the project (Prefix.pch).

Declared In

AFHTTPClient.h

operationQueue

The operation queue which manages operations enqueued by the HTTP client.

@property (readonly, nonatomic) NSOperationQueue *operationQueue

Discussion

The operation queue which manages operations enqueued by the HTTP client.

Declared In

AFHTTPClient.h

parameterEncoding

The AFHTTPClientParameterEncoding value corresponding to how parameters are encoded into a request body. This is AFFormURLParameterEncoding by default.

@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding

Discussion

The AFHTTPClientParameterEncoding value corresponding to how parameters are encoded into a request body. This is AFFormURLParameterEncoding by default.

Warning: Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. @{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as AFJSONParameterEncoding, is used when posting complicated or nondeterministic parameter structures.

Declared In

AFHTTPClient.h

stringEncoding

The string encoding used in constructing url requests. This is NSUTF8StringEncoding by default.

@property (nonatomic, assign) NSStringEncoding stringEncoding

Discussion

The string encoding used in constructing url requests. This is NSUTF8StringEncoding by default.

Declared In

AFHTTPClient.h

Class Methods

clientWithBaseURL:

Creates and initializes an AFHTTPClient object with the specified base URL.

+ (instancetype)clientWithBaseURL:(NSURL *)url

Parameters

url

The base URL for the HTTP client. This argument must not be nil.

Return Value

The newly-initialized HTTP client

Discussion

Creates and initializes an AFHTTPClient object with the specified base URL.

Declared In

AFHTTPClient.h

Instance Methods

HTTPRequestOperationWithRequest:success:failure:

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

urlRequest

The request object to be loaded asynchronously during execution of the operation.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation.

In order to determine what kind of operation is created, each registered subclass conforming to the AFHTTPClient protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return YES when sent a canProcessRequest: message is used to generate an operation using HTTPRequestOperationWithRequest:success:failure:.

Declared In

AFHTTPClient.h

cancelAllHTTPOperationsWithMethod:path:

Cancels all operations in the HTTP client’s operation queue whose URLs match the specified HTTP method and path.

- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path

Parameters

method

The HTTP method to match for the cancelled requests, such as GET, POST, PUT, or DELETE. If nil, all request operations with URLs matching the path will be cancelled.

path

The path appended to the HTTP client base URL to match against the cancelled requests. If nil, no path will be appended to the base URL.

@discussion This method only cancels AFHTTPRequestOperations whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the operationQueue property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use -cancelAllRequests. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation’s request property.

Discussion

Cancels all operations in the HTTP client’s operation queue whose URLs match the specified HTTP method and path.

Declared In

AFHTTPClient.h

clearAuthorizationHeader

Clears any existing value for the “Authorization” HTTP header.

- (void)clearAuthorizationHeader

Discussion

Clears any existing value for the “Authorization” HTTP header.

Declared In

AFHTTPClient.h

defaultValueForHeader:

Returns the value for the HTTP headers set in request objects created by the HTTP client.

- (NSString *)defaultValueForHeader:(NSString *)header

Parameters

header

The HTTP header to return the default value for

Return Value

The default value for the HTTP header, or nil if unspecified

Discussion

Returns the value for the HTTP headers set in request objects created by the HTTP client.

Declared In

AFHTTPClient.h

deletePath:parameters:success:failure:

Creates an AFHTTPRequestOperation with a DELETE request, and enqueues it to the HTTP client’s operation queue.

- (void)deletePath:(NSString *)path parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and appended as the query string for the request URL.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation with a DELETE request, and enqueues it to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock:

Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations progressBlock:(void ( ^ ) ( NSUInteger numberOfFinishedOperations , NSUInteger totalNumberOfOperations ))progressBlock completionBlock:(void ( ^ ) ( NSArray *operations ))completionBlock

Parameters

operations

The request operations used to be batched and enqueued.

progressBlock

A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.

completionBlock

A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.

Discussion

Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.

Declared In

AFHTTPClient.h

enqueueBatchOfHTTPRequestOperationsWithRequests:progressBlock:completionBlock:

Creates and enqueues an AFHTTPRequestOperation to the HTTP client’s operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.

- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests progressBlock:(void ( ^ ) ( NSUInteger numberOfFinishedOperations , NSUInteger totalNumberOfOperations ))progressBlock completionBlock:(void ( ^ ) ( NSArray *operations ))completionBlock

Parameters

urlRequests

The NSURLRequest objects used to create and enqueue operations.

progressBlock

A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations.

completionBlock

A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations.

@discussion Operations are created by passing the specified NSURLRequest objects in requests, using HTTPRequestOperationWithRequest:success:failure:, with nil for both the success and failure parameters.

Discussion

Creates and enqueues an AFHTTPRequestOperation to the HTTP client’s operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes.

Declared In

AFHTTPClient.h

enqueueHTTPRequestOperation:

Enqueues an AFHTTPRequestOperation to the HTTP client’s operation queue.

- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation

Parameters

operation

The HTTP request operation to be enqueued.

Discussion

Enqueues an AFHTTPRequestOperation to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

getPath:parameters:success:failure:

Creates an AFHTTPRequestOperation with a GET request, and enqueues it to the HTTP client’s operation queue.

- (void)getPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and appended as the query string for the request URL.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation with a GET request, and enqueues it to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

initWithBaseURL:

Initializes an AFHTTPClient object with the specified base URL.

- (id)initWithBaseURL:(NSURL *)url

Parameters

url

The base URL for the HTTP client. This argument must not be nil.

@discussion This is the designated initializer.

Return Value

The newly-initialized HTTP client

Discussion

Initializes an AFHTTPClient object with the specified base URL.

Declared In

AFHTTPClient.h

multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:

Creates an NSMutableURLRequest object with the specified HTTP method and path, and constructs a multipart/form-data HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2

- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void ( ^ ) ( id<AFMultipartFormData> formData ))block

Parameters

method

The HTTP method for the request. This parameter must not be GET or HEAD, or nil.

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and set in the request HTTP body.

block

A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the AFMultipartFormData protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values.

@discussion Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting NSMutableURLRequest object has an HTTPBodyStream property, so refrain from setting HTTPBodyStream or HTTPBody on this request object, as it will clear out the multipart form body stream.

Return Value

An NSMutableURLRequest object

Discussion

Creates an NSMutableURLRequest object with the specified HTTP method and path, and constructs a multipart/form-data HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2

Declared In

AFHTTPClient.h

patchPath:parameters:success:failure:

Creates an AFHTTPRequestOperation with a PATCH request, and enqueues it to the HTTP client’s operation queue.

- (void)patchPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and set in the request HTTP body.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation with a PATCH request, and enqueues it to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

postPath:parameters:success:failure:

Creates an AFHTTPRequestOperation with a POST request, and enqueues it to the HTTP client’s operation queue.

- (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and set in the request HTTP body.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation with a POST request, and enqueues it to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

putPath:parameters:success:failure:

Creates an AFHTTPRequestOperation with a PUT request, and enqueues it to the HTTP client’s operation queue.

- (void)putPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void ( ^ ) ( AFHTTPRequestOperation *operation , id responseObject ))success failure:(void ( ^ ) ( AFHTTPRequestOperation *operation , NSError *error ))failure

Parameters

path

The path to be appended to the HTTP client’s base URL and used as the request URL.

parameters

The parameters to be encoded and set in the request HTTP body.

success

A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request.

failure

A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the NSError object describing the network or parsing error that occurred.

Discussion

Creates an AFHTTPRequestOperation with a PUT request, and enqueues it to the HTTP client’s operation queue.

Declared In

AFHTTPClient.h

registerHTTPOperationClass:

Attempts to register a subclass of AFHTTPRequestOperation, adding it to a chain to automatically generate request operations from a URL request.

- (BOOL)registerHTTPOperationClass:(Class)operationClass

Parameters

operationClass

The subclass of AFHTTPRequestOperation to register

Return Value

YES if the registration is successful, NO otherwise. The only failure condition is if operationClass is not a subclass of AFHTTPRequestOperation.

@discussion When enqueueHTTPRequestOperationWithRequest:success:failure is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return YES when sent a canProcessRequest: message is used to create an operation using initWithURLRequest: and do setCompletionBlockWithSuccess:failure:. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list.

Discussion

Attempts to register a subclass of AFHTTPRequestOperation, adding it to a chain to automatically generate request operations from a URL request.

Declared In

AFHTTPClient.h

requestWithMethod:path:parameters:

Creates an NSMutableURLRequest object with the specified HTTP method and path.

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters

Parameters

method

The HTTP method for the request, such as GET, POST, PUT, or DELETE. This parameter must not be nil.

path

The path to be appended to the HTTP client’s base URL and used as the request URL. If nil, no path will be appended to the base URL.

parameters

The parameters to be either set as a query string for GET requests, or the request HTTP body.

Return Value

An NSMutableURLRequest object

Discussion

Creates an NSMutableURLRequest object with the specified HTTP method and path.

If the HTTP method is GET, HEAD, or DELETE, the parameters will be used to construct a url-encoded query string that is appended to the request’s URL. Otherwise, the parameters will be encoded according to the value of the parameterEncoding property, and set as the request body.

Declared In

AFHTTPClient.h

setAuthorizationHeaderWithToken:

Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.

- (void)setAuthorizationHeaderWithToken:(NSString *)token

Parameters

token

The authentication token

Discussion

Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header.

Declared In

AFHTTPClient.h

setAuthorizationHeaderWithUsername:password:

Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.

- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password

Parameters

username

The HTTP basic auth username

password

The HTTP basic auth password

Discussion

Sets the “Authorization” HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header.

Declared In

AFHTTPClient.h

setDefaultHeader:value:

Sets the value for the HTTP headers set in request objects made by the HTTP client. If nil, removes the existing value for that header.

- (void)setDefaultHeader:(NSString *)header value:(NSString *)value

Parameters

header

The HTTP header to set a default value for

value

The value set as default for the specified header, or `nil

Discussion

Sets the value for the HTTP headers set in request objects made by the HTTP client. If nil, removes the existing value for that header.

Declared In

AFHTTPClient.h

setReachabilityStatusChangeBlock:

Sets a callback to be executed when the network availability of the baseURL host changes.

- (void)setReachabilityStatusChangeBlock:(void ( ^ ) ( AFNetworkReachabilityStatus status ))block

Parameters

block

A block object to be executed when the network availability of the baseURL host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the baseURL.

Discussion

Sets a callback to be executed when the network availability of the baseURL host changes.

Warning: This method requires the SystemConfiguration framework. Add it in the active target’s “Link Binary With Library” build phase, and add #import <SystemConfiguration/SystemConfiguration.h> to the header prefix of the project (Prefix.pch).

Declared In

AFHTTPClient.h

unregisterHTTPOperationClass:

Unregisters the specified subclass of AFHTTPRequestOperation from the chain of classes consulted when -requestWithMethod:path:parameters is called.

- (void)unregisterHTTPOperationClass:(Class)operationClass

Parameters

operationClass

The subclass of AFHTTPRequestOperation to register

Discussion

Unregisters the specified subclass of AFHTTPRequestOperation from the chain of classes consulted when -requestWithMethod:path:parameters is called.

Declared In

AFHTTPClient.h