___              _ _ ____
   /   |  __________(_|_) __ \____  _  ____  __
  / /| | / ___/ ___/ / / / / / __ \| |/_/ / / /
 / ___ |(__  ) /__/ / / /_/ / /_/ />  </ /_/ /
/_/  |_/____/\___/_/_/_____/\____/_/|_|\__, /
                                      /____/

Swift transcoded from Objective C

This is an example demonstrating documentation for an Objective C project transcoded to Swift. The used source code files come from the AFNetworking project.

This is not meant to be complete documentation. Some links in the documentation may not work due to missing documentation.
Doxygen configuration
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.

OUTPUT_DIRECTORY       = $(OUTPUT_DIR)

# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
# The default value is: YES.

GENERATE_HTML          = NO

# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
# The default value is: YES.

GENERATE_LATEX         = NO

# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.

GENERATE_XML           = YES

# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,
# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice,
# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
# tries to guess whether the code is fixed or free formatted code, this is the
# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat
# .inc files as Fortran files (default is PHP), and .f files as C (default is
# Fortran), use: inc=Fortran f=C.
#
# Note: For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.

EXTENSION_MAPPING      = h=objective-c

# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
# in the source code. If set to NO, only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

MACRO_EXPANSION        = YES
#
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

EXPAND_ONLY_PREDEF     = YES

# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.

PREDEFINED             = NS_ASSUME_NONNULL_BEGIN= NS_UNAVAILABLE= NS_DESIGNATED_INITIALIZER=
AsciiDoxy directives
${language("swift", source="objc")}
${insert("AFHTTPSessionManager")}
${insert("AFHTTPRequestSerializer")}
${insert("AFURLRequestSerialization")}
${insert("AFMultipartFormData")}

AFHTTPSessionManager

class AFHTTPSessionManager

AFHTTPSessionManager is a subclass of AFURLSessionManager with convenience methods for making HTTP requests. When a baseURL is provided, requests made with the GET / POST / et al. convenience methods can be made with relative paths.

Subclassing Notes

Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass AFHTTPSessionManager, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.

Methods to Override

To change the behavior of all data task operation construction, which is also used in the GET / POST / et al. convenience methods, override dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:.

Serialization

Requests created by an HTTP client will contain default headers and encode parameters according to the requestSerializer property, which is an object conforming to <AFURLRequestSerialization>.

Responses received from the server are automatically validated and serialized by the responseSerializers property, which is an object conforming to <AFURLResponseSerialization>

URL Construction Using Relative Paths

For HTTP convenience methods, the request serializer constructs URLs from the path relative to the -baseURL, using NSURL +URLWithString:relativeToURL:, when provided. If baseURL is nil, path needs to resolve to a valid NSURL object using NSURL +URLWithString:.

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. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash.

Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance.

Public Constructors

init(URL?)

Initializes an AFHTTPSessionManager object with the specified base URL.

init(URL?, URLSessionConfiguration?)

Initializes an AFHTTPSessionManager object with the specified base URL.

Public Properties

baseURL

The URL used to construct requests from relative paths in methods like requestWithMethod:URLString:parameters:, and the GET / POST / et al. convenience methods.

requestSerializer

Requests created with requestWithMethod:URLString:parameters: & multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock: are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of AFHTTPRequestSerializer, which serializes query string parameters for GET, HEAD, and DELETE requests, or otherwise URL-form-encodes HTTP message bodies.

responseSerializer

Responses sent from the server in data tasks created with dataTaskWithRequest:success:failure: and run using the GET / POST / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of AFJSONResponseSerializer.

securityPolicy

Public Type Methods

Public Methods

GET(String, Any?, Dictionary<String, String>?, ((downloadProgress: Progress) -> void)?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)
HEAD(String, Any?, Dictionary<String, String>?, ((task: URLSessionDataTask) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a HEAD request.

POST(String, Any?, Dictionary<String, String>?, ((uploadProgress: Progress) -> void)?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a POST request.

POST(String, Any?, Dictionary<String, String>?, ((formData: AFMultipartFormData) -> void)?, ((uploadProgress: Progress) -> void)?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a multipart POST request.

PUT(String, Any?, Dictionary<String, String>?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a PUT request.

PATCH(String, Any?, Dictionary<String, String>?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a PATCH request.

DELETE(String, Any?, Dictionary<String, String>?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates and runs an NSURLSessionDataTask with a DELETE request.

dataTask(String, String, Any?, Dictionary<String, String>?, ((uploadProgress: Progress) -> void)?, ((downloadProgress: Progress) -> void)?, ((task: URLSessionDataTask, responseObject: Any?) -> void)?, ((task: URLSessionDataTask?, error: Error) -> void)?)

Creates an NSURLSessionDataTask with a custom HTTPMethod request.

Members

func init(baseURL: URL?)

Initializes an AFHTTPSessionManager object with the specified base URL.

Parameters

baseURL: URL?

The base URL for the HTTP client.


func init(baseURL: URL?,
          configuration: URLSessionConfiguration?)

Initializes an AFHTTPSessionManager object with the specified base URL.

This is the designated initializer.

Parameters

baseURL: URL?

The base URL for the HTTP client.

configuration: URLSessionConfiguration?

The configuration used to create the managed session.


var baseURL: URL

The URL used to construct requests from relative paths in methods like requestWithMethod:URLString:parameters:, and the GET / POST / et al. convenience methods.


Requests created with requestWithMethod:URLString:parameters: & multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock: are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of AFHTTPRequestSerializer, which serializes query string parameters for GET, HEAD, and DELETE requests, or otherwise URL-form-encodes HTTP message bodies.

requestSerializer must not be nil.


var responseSerializer: AFHTTPResponseSerializer<AFURLResponseSerialization>

Responses sent from the server in data tasks created with dataTaskWithRequest:success:failure: and run using the GET / POST / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of AFJSONResponseSerializer.

responseSerializer must not be nil.


var securityPolicy: AFSecurityPolicy

@name Managing Security Policy

The security policy used by created session to evaluate server trust for secure connections. AFURLSessionManager uses the defaultPolicy unless otherwise specified. A security policy configured with AFSSLPinningModePublicKey or AFSSLPinningModeCertificate can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an Invalid Security Policy exception.


func manager() -> instancetype

@name Initialization

Creates and returns an AFHTTPSessionManager object.

Returns

instancetype

func GET(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    downloadProgress: ((downloadProgress: Progress) -> void)?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

@name Making HTTP Requests

Creates and runs an NSURLSessionDataTask with a GET request.

See

-dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

downloadProgress: ((downloadProgress: Progress) → void)?

A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func HEAD(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    success: ((task: URLSessionDataTask) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a HEAD request.

See

-dataTaskWithRequest:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

success: ((task: URLSessionDataTask) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func POST(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    uploadProgress: ((uploadProgress: Progress) -> void)?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a POST request.

See

-dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

uploadProgress: ((uploadProgress: Progress) → void)?

A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func POST(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    block: ((formData: AFMultipartFormData) -> void)?,
    uploadProgress: ((uploadProgress: Progress) -> void)?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a multipart POST request.

See

-dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

block: ((formData: AFMultipartFormData) → void)?

A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the AFMultipartFormData protocol.

uploadProgress: ((uploadProgress: Progress) → void)?

A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func PUT(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a PUT request.

See

-dataTaskWithRequest:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func PATCH(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a PATCH request.

See

-dataTaskWithRequest:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func DELETE(
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates and runs an NSURLSessionDataTask with a DELETE request.

See

-dataTaskWithRequest:completionHandler:

Parameters

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

func dataTask(
    withHTTPMethod: String,
    URLString: String,
    parameters: Any?,
    headers: Dictionary<String, String>?,
    uploadProgress: ((uploadProgress: Progress) -> void)?,
    downloadProgress: ((downloadProgress: Progress) -> void)?,
    success: ((task: URLSessionDataTask, responseObject: Any?) -> void)?,
    failure: ((task: URLSessionDataTask?, error: Error) -> void)?) -> URLSessionDataTask?

Creates an NSURLSessionDataTask with a custom HTTPMethod request.

See

-dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:

Parameters

withHTTPMethod: String

The HTTPMethod string used to create the request.

URLString: String

The URL string used to create the request URL.

parameters: Any?

The parameters to be encoded according to the client request serializer.

headers: Dictionary<String, String>?

The headers appended to the default headers for this request.

uploadProgress: ((uploadProgress: Progress) → void)?

A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.

downloadProgress: ((downloadProgress: Progress) → void)?

A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.

success: ((task: URLSessionDataTask, responseObject: Any?) → void)?

A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer.

failure: ((task: URLSessionDataTask?, error: Error) → void)?

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

Returns

URLSessionDataTask?

AFHTTPRequestSerializer

class AFHTTPRequestSerializer

AFHTTPRequestSerializer conforms to the AFURLRequestSerialization & AFURLResponseSerialization protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation.

Any request or response serializer dealing with HTTP is encouraged to subclass AFHTTPRequestSerializer in order to ensure consistent default behavior.

Public Properties

stringEncoding

The string encoding used to serialize parameters. NSUTF8StringEncoding by default.

allowsCellularAccess

Whether created requests can use the device’s cellular radio (if present). YES by default.

cachePolicy

The cache policy of created requests. NSURLRequestUseProtocolCachePolicy by default.

HTTPShouldHandleCookies

Whether created requests should use the default cookie handling. YES by default.

HTTPShouldUsePipelining

Whether created requests can continue transmitting data before receiving a response from an earlier transmission. NO by default

networkServiceType

The network service type for created requests. NSURLNetworkServiceTypeDefault by default.

timeoutInterval

The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.

HTTPRequestHeaders
HTTPMethodsEncodingParametersInURI

Public Type Methods

serializer()

Creates and returns a serializer with default configuration.

Public Methods

setValue(String?, String)

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.

valueForHTTPHeaderField(String)

Returns the value for the HTTP headers set in the request serializer.

setAuthorizationHeaderField(String, String)

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.

clearAuthorizationHeader()

Clears any existing value for the "Authorization" HTTP header.

setQueryStringSerialization(AFHTTPRequestQueryStringSerializationStyle)

Set the method of query string serialization according to one of the pre-defined styles.

setQueryStringSerialization(((request: URLRequest, parameters: Any, error: Error) -> String)?)

Set the a custom method of query string serialization according to the specified block.

request(String, String, Any?)
multipartFormRequest(String, String, Dictionary<String, Any>?, ((formData: AFMultipartFormData) -> void)?)

Creates an NSMutableURLRequest object with the specified HTTP method and URLString, 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

request(URLRequest, URL, ((error: Error?) -> void)?)

Creates an NSMutableURLRequest by removing the HTTPBodyStream from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.

Members

var stringEncoding: StringEncoding

The string encoding used to serialize parameters. NSUTF8StringEncoding by default.


var allowsCellularAccess: Bool

Whether created requests can use the device’s cellular radio (if present). YES by default.

See

NSMutableURLRequest -setAllowsCellularAccess:


var cachePolicy: URLRequestCachePolicy

The cache policy of created requests. NSURLRequestUseProtocolCachePolicy by default.

See

NSMutableURLRequest -setCachePolicy:


var HTTPShouldHandleCookies: Bool

Whether created requests should use the default cookie handling. YES by default.

See

NSMutableURLRequest -setHTTPShouldHandleCookies:


var HTTPShouldUsePipelining: Bool

Whether created requests can continue transmitting data before receiving a response from an earlier transmission. NO by default

See

NSMutableURLRequest -setHTTPShouldUsePipelining:


var networkServiceType: URLRequestNetworkServiceType

The network service type for created requests. NSURLNetworkServiceTypeDefault by default.

See

NSMutableURLRequest -setNetworkServiceType:


var timeoutInterval: TimeInterval

The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds.

See

NSMutableURLRequest -setTimeoutInterval:


var HTTPRequestHeaders: Dictionary<String, String>

@name Configuring HTTP Request Headers

Default HTTP header field values to be applied to serialized requests. By default, these include the following:

  • Accept-Language with the contents of NSLocale +preferredLanguages

  • User-Agent with the contents of various bundle identifiers and OS designations

@discussion To add or remove default request headers, use setValue:forHTTPHeaderField:.


var HTTPMethodsEncodingParametersInURI: Set<String>

@name Configuring Query String Parameter Serialization

HTTP methods for which serialized requests will encode parameters as a query string. GET, HEAD, and DELETE by default.


func serializer() -> instancetype

Creates and returns a serializer with default configuration.

Returns

instancetype

func setValue(value: String?,
              field: String)

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

value: String?

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

field: String

The HTTP header to set a default value for


func valueForHTTPHeaderField(field: String) -> String?

Returns the value for the HTTP headers set in the request serializer.

Parameters

field: String

The HTTP header to retrieve the default value for

Returns

String?

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


func setAuthorizationHeaderField(withUsername: String,
                                 password: String)

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

withUsername: String

The HTTP basic auth username

password: String

The HTTP basic auth password


func clearAuthorizationHeader()

Clears any existing value for the "Authorization" HTTP header.


func setQueryStringSerialization(
    withStyle: AFHTTPRequestQueryStringSerializationStyle)

Set the method of query string serialization according to one of the pre-defined styles.

See

AFHTTPRequestQueryStringSerializationStyle

Parameters

withStyle: AFHTTPRequestQueryStringSerializationStyle

The serialization style.


func setQueryStringSerialization(
    withBlock: ((request: URLRequest, parameters: Any, error: Error) -> String)?)

Set the a custom method of query string serialization according to the specified block.

Parameters

withBlock: ((request: URLRequest, parameters: Any, error: Error) → String)?

A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request.


func request(withMethod: String,
             URLString: String,
             parameters: Any?) throws -> MutableURLRequest

@name Creating Request Objects

Creates an NSMutableURLRequest object with the specified HTTP method and URL string.

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

withMethod: String

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

URLString: String

The URL string used to create the request URL.

parameters: Any?

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

Returns

MutableURLRequest

An NSMutableURLRequest object.

Throws

Error?

The error that occurred while constructing the request.


func multipartFormRequest(
    withMethod: String,
    URLString: String,
    parameters: Dictionary<String, Any>?,
    block: ((formData: AFMultipartFormData) -> void)?) throws -> MutableURLRequest

Creates an NSMutableURLRequest object with the specified HTTP method and URLString, 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

withMethod: String

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

URLString: String

The URL string used to create the request URL.

parameters: Dictionary<String, Any>?

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

block: ((formData: AFMultipartFormData) → void)?

A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the AFMultipartFormData protocol.

Returns

MutableURLRequest

An NSMutableURLRequest object

Throws

Error?

The error that occurred while constructing the request.


func request(withMultipartFormRequest: URLRequest,
             fileURL: URL,
             handler: ((error: Error?) -> void)?) -> MutableURLRequest

Creates an NSMutableURLRequest by removing the HTTPBodyStream from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished.

NSURLSessionTask that causes requests to not send a Content-Length header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:, or any other request with an HTTPBodyStream, writes the contents to the specified file and returns a copy of the original request with the HTTPBodyStream property set to nil. From here, the file can either be passed to AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:, or have its contents read into an NSData that’s assigned to the HTTPBody property of the request.

Parameters

withMultipartFormRequest: URLRequest

The multipart form request. The HTTPBodyStream property of request must not be nil.

fileURL: URL

The file URL to write multipart form contents to.

handler: ((error: Error?) → void)?

A handler block to execute.

Returns

MutableURLRequest

AFURLRequestSerialization

protocol AFURLRequestSerialization

The AFURLRequestSerialization protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary.

For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the Content-Type HTTP header field value to application/json.

Public Methods

requestBySerializingRequest(URLRequest, Any?, Error?)

Returns a request with the specified parameters encoded into a copy of the original request.

Members

func requestBySerializingRequest(request: URLRequest,
                                 parameters: Any?,
                                 NS_SWIFT_NOTHROW: Error?) -> URLRequest?

Returns a request with the specified parameters encoded into a copy of the original request.

Parameters

request: URLRequest

The original request.

parameters: Any?

The parameters to be encoded.

NS_SWIFT_NOTHROW: Error?

Returns

URLRequest?

A serialized request.


AFMultipartFormData

protocol AFMultipartFormData

The AFMultipartFormData protocol defines the methods supported by the parameter in the block argument of AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:.

Public Methods

appendPart(URL, String)

Appends the HTTP header Content-Disposition: file; filename={generated filename}; name={name}" and Content-Type: #{generated mimeType}, followed by the encoded file data and the multipart form boundary.

appendPart(URL, String, String, String)

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the encoded file data and the multipart form boundary.

appendPart(InputStream?, String, String, int64_t, String)

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the data from the input stream and the multipart form boundary.

appendPart(Data, String, String, String)

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the encoded file data and the multipart form boundary.

appendPart(Data, String)

Appends the HTTP headers Content-Disposition: form-data; name=#{name}", followed by the encoded data and the multipart form boundary.

appendPart(Dictionary<String, String>?, Data)

Appends HTTP headers, followed by the encoded data and the multipart form boundary.

throttleBandwidth(UInteger, TimeInterval)

Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.

Members

func appendPart(withFileURL: URL,
                name: String) throws

Appends the HTTP header Content-Disposition: file; filename={generated filename}; name={name}" and Content-Type: #{generated mimeType}, followed by the encoded file data and the multipart form boundary.

The filename and MIME type for this data in the form will be automatically generated, using the last path component of the fileURL and system associated MIME type for the fileURL extension, respectively.

Parameters

withFileURL: URL

The URL corresponding to the file whose content will be appended to the form. This parameter must not be nil.

name: String

The name to be associated with the specified data. This parameter must not be nil.

Throws

Error?

If an error occurs, upon return contains an NSError object that describes the problem.


func appendPart(withFileURL: URL,
                name: String,
                fileName: String,
                mimeType: String) throws

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the encoded file data and the multipart form boundary.

Parameters

withFileURL: URL

The URL corresponding to the file whose content will be appended to the form. This parameter must not be nil.

name: String

The name to be associated with the specified data. This parameter must not be nil.

fileName: String

The file name to be used in the Content-Disposition header. This parameter must not be nil.

mimeType: String

The declared MIME type of the file data. This parameter must not be nil.

Throws

Error?

If an error occurs, upon return contains an NSError object that describes the problem.


func appendPart(withInputStream: InputStream?,
                name: String,
                fileName: String,
                length: int64_t,
                mimeType: String)

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the data from the input stream and the multipart form boundary.

Parameters

withInputStream: InputStream?

The input stream to be appended to the form data

name: String

The name to be associated with the specified input stream. This parameter must not be nil.

fileName: String

The filename to be associated with the specified input stream. This parameter must not be nil.

length: int64_t

The length of the specified input stream in bytes.

mimeType: String

The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be nil.


func appendPart(withFileData: Data,
                name: String,
                fileName: String,
                mimeType: String)

Appends the HTTP header Content-Disposition: file; filename={filename}; name={name}" and Content-Type: #{mimeType}, followed by the encoded file data and the multipart form boundary.

Parameters

withFileData: Data

The data to be encoded and appended to the form data.

name: String

The name to be associated with the specified data. This parameter must not be nil.

fileName: String

The filename to be associated with the specified data. This parameter must not be nil.

mimeType: String

The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be nil.


func appendPart(withFormData: Data,
                name: String)

Appends the HTTP headers Content-Disposition: form-data; name=#{name}", followed by the encoded data and the multipart form boundary.

Parameters

withFormData: Data

The data to be encoded and appended to the form data.

name: String

The name to be associated with the specified data. This parameter must not be nil.


func appendPart(withHeaders: Dictionary<String, String>?,
                body: Data)

Appends HTTP headers, followed by the encoded data and the multipart form boundary.

Parameters

withHeaders: Dictionary<String, String>?

The HTTP headers to be appended to the form data.

body: Data

The data to be encoded and appended to the form data. This parameter must not be nil.


func throttleBandwidth(withPacketSize: UInteger,
                       delay: TimeInterval)

Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream.

When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (kAFUploadStream3GSuggestedPacketSize and kAFUploadStream3GSuggestedDelay) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over NSURLConnection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth.

Parameters

withPacketSize: UInteger

Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb.

delay: TimeInterval

Duration of delay each time a packet is read. By default, no delay is set.


AsciiDoxy