AFURLConnectionOperation Class Reference
| Inherits from | NSOperation |
| Conforms to | NSCoding NSCopying NSURLConnectionDataDelegate NSURLConnectionDelegate |
| Declared in | AFURLConnectionOperation.h AFURLConnectionOperation.m |
Overview
AFURLConnectionOperation is a subclass of NSOperation that implements NSURLConnection delegate methods.
Subclassing Notes
This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional NSURLConnection delegate methods (see “NSURLConnection Delegate Methods” below), or to provide additional properties and/or class constructors.
If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing AFHTTPRequestOperation instead, as it supports specifying acceptable content types or status codes.
NSURLConnection Delegate Methods
AFURLConnectionOperation implements the following NSURLConnection delegate methods:
connection:didReceiveResponse:connection:didReceiveData:connectionDidFinishLoading:connection:didFailWithError:connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:connection:willCacheResponse:connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge:
If any of these methods are overridden in a subclass, they must call the super implementation first.
Class Constructors
Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, AFJSONRequestOperation provides JSONRequestOperationWithRequest:success:failure:, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the response data.
Callbacks and Completion Blocks
The built-in completionBlock provided by NSOperation allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its completionBlock. Make sure to handle cancelled operations appropriately when setting a completionBlock (i.e. returning early before parsing response data). See the implementation of any of the AFHTTPRequestOperation subclasses for an example of this.
Subclasses are strongly discouraged from overriding setCompletionBlock:, as AFURLConnectionOperation’s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as “The Deallocation Problem”.
NSCoding & NSCopying Conformance
AFURLConnectionOperation conforms to the NSCoding and NSCopying protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind:
NSCoding Caveats
- Encoded operations do not include any block or stream properties. Be sure to set
completionBlock,outputStream, and any callback blocks as necessary when using-initWithCoder:orNSKeyedUnarchiver. - Operations are paused on
encodeWithCoder:. If the operation was encoded while paused or still executing, its archived state will returnYESforisReady. Otherwise, the state of an operation when encoding will remain unchanged.
NSCopying Caveats
-copyand-copyWithZone:return a new operation with theNSURLRequestof the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations.- A copy of an operation will not include the
outputStreamof the original. - Operation copies do not include
completionBlock.completionBlockoften strongly captures a reference toself, which would otherwise have the unintuitive side-effect of pointing to the original operation when copied.
Tasks
Accessing Run Loop Modes
-
runLoopModesThe run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing
propertyNSRunLoopCommonModes.
Getting URL Connection Information
-
requestThe request used by the operation’s connection.
property -
responseThe last response received by the operation’s connection.
property -
errorproperty
Getting Response Data
-
responseDataThe data received during the request.
property -
responseStringThe string representation of the response data.
property
Accessing Streams
-
inputStreamThe input stream used to read data to be sent during the request.
property -
outputStreamThe output stream that is used to write data received until the request is finished.
property
Initializing an AFURLConnectionOperation Object
-
– initWithRequest:Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
Pausing / Resuming Requests
-
– pausePauses the execution of the request operation.
-
– isPausedWhether the request operation is currently paused.
-
– resumeResumes the execution of the paused request operation.
Configuring Backgrounding Task Behavior
-
– setShouldExecuteAsBackgroundTaskWithExpirationHandler:Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
Setting Progress Callbacks
-
– setUploadProgressBlock:Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
-
– setDownloadProgressBlock:Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
Setting NSURLConnection Delegate Callbacks
-
– setAuthenticationAgainstProtectionSpaceBlock:Sets a block to be executed to determine whether the connection should be able to respond to a protection space’s form of authentication, as handled by the
NSURLConnectionDelegatemethodconnection:canAuthenticateAgainstProtectionSpace:. -
– setAuthenticationChallengeBlock:Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the
NSURLConnectionDelegatemethodconnection:didReceiveAuthenticationChallenge:. -
– setRedirectResponseBlock:Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the
NSURLProtocolsubclass handling the request in order to standardize its format, as handled by theNSURLConnectionDelegatemethodconnection:willSendRequest:redirectResponse:. -
– setCacheResponseBlock:Sets a block to be executed to modify the response a connection will cache, if any, as handled by the
NSURLConnectionDelegatemethodconnection:willCacheResponse:.
Properties
inputStream
The input stream used to read data to be sent during the request.
@property (nonatomic, strong) NSInputStream *inputStreamDiscussion
The input stream used to read data to be sent during the request.
@discussion This property acts as a proxy to the HTTPBodyStream property of request.
Declared In
AFURLConnectionOperation.houtputStream
The output stream that is used to write data received until the request is finished.
@property (nonatomic, strong) NSOutputStream *outputStreamDiscussion
The output stream that is used to write data received until the request is finished.
@discussion By default, data is accumulated into a buffer that is stored into responseData upon completion of the request. When outputStream is set, the data will not be accumulated into an internal buffer, and as a result, the responseData property of the completed request will be nil. The output stream will be scheduled in the network thread runloop upon being set.
Declared In
AFURLConnectionOperation.hrequest
The request used by the operation’s connection.
@property (readonly, nonatomic, strong) NSURLRequest *requestDiscussion
The request used by the operation’s connection.
Declared In
AFURLConnectionOperation.hresponse
The last response received by the operation’s connection.
@property (readonly, nonatomic, strong) NSURLResponse *responseDiscussion
The last response received by the operation’s connection.
Declared In
AFURLConnectionOperation.hresponseData
The data received during the request.
@property (readonly, nonatomic, strong) NSData *responseDataDiscussion
The data received during the request.
Declared In
AFURLConnectionOperation.hresponseString
The string representation of the response data.
@property (readonly, nonatomic, copy) NSString *responseStringDiscussion
The string representation of the response data.
@discussion This method uses the string encoding of the response, or if UTF-8 if not specified, to construct a string from the response data.
Declared In
AFURLConnectionOperation.hrunLoopModes
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing NSRunLoopCommonModes.
@property (nonatomic, strong) NSSet *runLoopModesDiscussion
The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing NSRunLoopCommonModes.
Declared In
AFURLConnectionOperation.hInstance Methods
initWithRequest:
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
- (id)initWithRequest:(NSURLRequest *)urlRequestParameters
- urlRequest
The request object to be used by the operation connection.
@discussion This is the designated initializer.
Discussion
Initializes and returns a newly allocated operation object with a url connection configured with the specified url request.
Declared In
AFURLConnectionOperation.hisPaused
Whether the request operation is currently paused.
- (BOOL)isPausedReturn Value
YES if the operation is currently paused, otherwise NO.
Discussion
Whether the request operation is currently paused.
Declared In
AFURLConnectionOperation.hpause
Pauses the execution of the request operation.
- (void)pauseDiscussion
Pauses the execution of the request operation.
@discussion A paused operation returns NO for isReady, isExecuting, and isFinished. As such, it will remain in an NSOperationQueue until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect.
Declared In
AFURLConnectionOperation.hresume
Resumes the execution of the paused request operation.
- (void)resumeDiscussion
Resumes the execution of the paused request operation.
@discussion Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, AFHTTPRequestOperation will resume downloading the request from where it left off, instead of restarting the original request.
Declared In
AFURLConnectionOperation.hsetAuthenticationAgainstProtectionSpaceBlock:
Sets a block to be executed to determine whether the connection should be able to respond to a protection space’s form of authentication, as handled by the NSURLConnectionDelegate method connection:canAuthenticateAgainstProtectionSpace:.
- (void)setAuthenticationAgainstProtectionSpaceBlock:(BOOL ( ^ ) ( NSURLConnection *connection , NSURLProtectionSpace *protectionSpace ))blockParameters
- block
A block object to be executed to determine whether the connection should be able to respond to a protection space’s form of authentication. The block has a
BOOLreturn type and takes two arguments: the URL connection object, and the protection space to authenticate against.@discussion If
_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_is defined,connection:canAuthenticateAgainstProtectionSpace:will accept invalid SSL certificates, returningYESif the protection space authentication method isNSURLAuthenticationMethodServerTrust.
Discussion
Sets a block to be executed to determine whether the connection should be able to respond to a protection space’s form of authentication, as handled by the NSURLConnectionDelegate method connection:canAuthenticateAgainstProtectionSpace:.
Declared In
AFURLConnectionOperation.hsetAuthenticationChallengeBlock:
Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the NSURLConnectionDelegate method connection:didReceiveAuthenticationChallenge:.
- (void)setAuthenticationChallengeBlock:(void ( ^ ) ( NSURLConnection *connection , NSURLAuthenticationChallenge *challenge ))blockParameters
- block
A block object to be executed when the connection must authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated.
@discussion If
_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_is defined,connection:didReceiveAuthenticationChallenge:will attempt to have the challenge sender use credentials with invalid SSL certificates.
Discussion
Sets a block to be executed when the connection must authenticate a challenge in order to download its request, as handled by the NSURLConnectionDelegate method connection:didReceiveAuthenticationChallenge:.
Declared In
AFURLConnectionOperation.hsetCacheResponseBlock:
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the NSURLConnectionDelegate method connection:willCacheResponse:.
- (void)setCacheResponseBlock:(NSCachedURLResponse *( ^ ) ( NSURLConnection *connection , NSCachedURLResponse *cachedResponse ))blockParameters
- block
A block object to be executed to determine what response a connection will cache, if any. The block returns an
NSCachedURLResponseobject, the cached response to store in memory ornilto prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request.
Discussion
Sets a block to be executed to modify the response a connection will cache, if any, as handled by the NSURLConnectionDelegate method connection:willCacheResponse:.
Declared In
AFURLConnectionOperation.hsetDownloadProgressBlock:
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
- (void)setDownloadProgressBlock:(void ( ^ ) ( NSUInteger bytesRead , long long totalBytesRead , long long totalBytesExpectedToRead ))blockParameters
- block
A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the
NSHTTPURLResponseobject. This block may be called multiple times, and will execute on the main thread.
Discussion
Sets a callback to be called when an undetermined number of bytes have been downloaded from the server.
Declared In
AFURLConnectionOperation.hsetRedirectResponseBlock:
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the NSURLProtocol subclass handling the request in order to standardize its format, as handled by the NSURLConnectionDelegate method connection:willSendRequest:redirectResponse:.
- (void)setRedirectResponseBlock:(NSURLRequest *( ^ ) ( NSURLConnection *connection , NSURLRequest *request , NSURLResponse *redirectResponse ))blockParameters
Discussion
Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the NSURLProtocol subclass handling the request in order to standardize its format, as handled by the NSURLConnectionDelegate method connection:willSendRequest:redirectResponse:.
Declared In
AFURLConnectionOperation.hsetShouldExecuteAsBackgroundTaskWithExpirationHandler:
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void ( ^ ) ( void ))handlerParameters
- handler
A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the
handlerparameter inUIApplication -beginBackgroundTaskWithExpirationHandler:, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified.
Discussion
Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task.
Declared In
AFURLConnectionOperation.hsetUploadProgressBlock:
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
- (void)setUploadProgressBlock:(void ( ^ ) ( NSUInteger bytesWritten , long long totalBytesWritten , long long totalBytesExpectedToWrite ))blockParameters
- block
A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread.
Discussion
Sets a callback to be called when an undetermined number of bytes have been uploaded to the server.
Declared In
AFURLConnectionOperation.h