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/"];
[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

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.

Managing URL Credentials

Creating Request Objects

Creating HTTP Operations

Managing Enqueued HTTP Operations

Batching HTTP Request Operations

Making HTTP Requests

Properties

allowsInvalidSSLCertificate

@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate
Discussion

Whether each AFHTTPRequestOperation created by HTTPRequestOperationWithRequest:success:failure: should accept an invalid SSL certificate.

If _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ is set, this property defaults to YES for backwards compatibility. Otherwise, this property defaults to NO.

Declared In

AFHTTPClient.h

baseURL

@property (readonly, nonatomic, strong) NSURL *baseURL
Discussion

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

Declared In

AFHTTPClient.h

defaultSSLPinningMode

@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode
Discussion

Default SSL pinning mode for each AFHTTPRequestOperation created by HTTPRequestOperationWithRequest:success:failure:.

Declared In

AFHTTPClient.h

networkReachabilityStatus

@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

@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue
Discussion

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

Declared In

AFHTTPClient.h

parameterEncoding

@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

@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:

+ (instancetype)clientWithBaseURL:(NSURL *)url
Discussion

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

Parameters

url

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

Return Value

The newly-initialized HTTP client

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
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:.

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.

Declared In

AFHTTPClient.h

cancelAllHTTPOperationsWithMethod:path:

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

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

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.

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.

Declared In

AFHTTPClient.h

clearAuthorizationHeader

- (void)clearAuthorizationHeader
Discussion

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

Declared In

AFHTTPClient.h

defaultValueForHeader:

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

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

Parameters

header

The HTTP header to return the default value for

Return Value

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

Declared In

AFHTTPClient.h

deletePath:parameters:success:failure:

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

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

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.

Declared In

AFHTTPClient.h

enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock:

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations progressBlock:(void ( ^ ) ( NSUInteger numberOfFinishedOperations , NSUInteger totalNumberOfOperations ))progressBlock completionBlock:(void ( ^ ) ( NSArray *operations ))completionBlock
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.

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.

Declared In

AFHTTPClient.h

enqueueBatchOfHTTPRequestOperationsWithRequests:progressBlock:completionBlock:

- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests progressBlock:(void ( ^ ) ( NSUInteger numberOfFinishedOperations , NSUInteger totalNumberOfOperations ))progressBlock completionBlock:(void ( ^ ) ( NSArray *operations ))completionBlock
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.

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

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.

Declared In

AFHTTPClient.h

enqueueHTTPRequestOperation:

- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation
Discussion

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

Parameters

operation

The HTTP request operation to be enqueued.

Declared In

AFHTTPClient.h

getPath:parameters:success:failure:

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

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

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.

Declared In

AFHTTPClient.h

initWithBaseURL:

- (id)initWithBaseURL:(NSURL *)url
Discussion

Initializes an AFHTTPClient object with the specified base URL.

This is the designated initializer.

Parameters

url

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

Return Value

The newly-initialized HTTP client

Declared In

AFHTTPClient.h

multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:

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

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.

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.

Return Value

An NSMutableURLRequest object

Declared In

AFHTTPClient.h

patchPath:parameters:success:failure:

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

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

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.

Declared In

AFHTTPClient.h

postPath:parameters:success:failure:

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

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

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.

Declared In

AFHTTPClient.h

putPath:parameters:success:failure:

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

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

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.

Declared In

AFHTTPClient.h

registerHTTPOperationClass:

- (BOOL)registerHTTPOperationClass:(Class)operationClass
Discussion

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

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.

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.

Declared In

AFHTTPClient.h

requestWithMethod:path:parameters:

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters
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.

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

Declared In

AFHTTPClient.h

setAuthorizationHeaderWithToken:

- (void)setAuthorizationHeaderWithToken:(NSString *)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.

Parameters

token

The authentication token

Declared In

AFHTTPClient.h

setAuthorizationHeaderWithUsername:password:

- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)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.

Parameters

username

The HTTP basic auth username

password

The HTTP basic auth password

Declared In

AFHTTPClient.h

setDefaultCredential:

- (void)setDefaultCredential:(NSURLCredential *)credential
Discussion

Set the default URL credential to be set for request operations.

Parameters

credential

The URL credential

Declared In

AFHTTPClient.h

setDefaultHeader:value:

- (void)setDefaultHeader:(NSString *)header value:(NSString *)value
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.

Parameters

header

The HTTP header to set a default value for

value

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

Declared In

AFHTTPClient.h

setReachabilityStatusChangeBlock:

- (void)setReachabilityStatusChangeBlock:(void ( ^ ) ( AFNetworkReachabilityStatus status ))block
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).

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.

Declared In

AFHTTPClient.h

unregisterHTTPOperationClass:

- (void)unregisterHTTPOperationClass:(Class)operationClass
Discussion

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

Parameters

operationClass

The subclass of AFHTTPRequestOperation to register

Declared In

AFHTTPClient.h