AFNetworking 2.0 extensions to add ReactiveCocoa
support with automatic retry based on a special condition (timeout or similar). Retry condition can be set as a block, also based on HTTP status code.
Library only extends AFHTTPSessionManager
for now with Reactive methods. For each HTTP operation a RACSignal
is returned. Under the hood, multiple calls are made to desired API endpoint and only after final retry the operation is errored.
For specific retry logic, a test block can be provided into the method, which will be evaluated on each retry. If operation returns YES
, the request will be retried.
The easiest way to install is with CocoaPods by specifying the pod in Podfile.
pod 'AFNetworking-RACRetryExtensions'
Alternatively you can download the .zip of the project and drag and drop files into your project (the manual way).
RACRetryExtensions provide a category to AFHTTPSessionManager
with multiple convenience methods that return an RACSignal
wrapped RACURLSessionRetryDataTask
. Methods provide different configuration options, such as: number of retries before failing, sleep delay before next retry and retry test block. First two parameters correspond to AFNetworking AFHTTPSessionManager
HTTP method and parameters.
Example of a HTTP GET method that connects to a simple website.
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
RACSignal* getSignal = [manager rac_GET:@"http://example.org" parameters:nil retries:3 interval:10.0];
// Subscribe to signal to start request
[getSignal subscribeNext:^(RACTuple *response) {
id object = [response first];
NSHTTPURLResponse urlResponse = [response second];
} error:^(NSError *error) {
// Handle error
}];
If the request fails from any reason, it will be retries 3 times. Before each retry attempt, task will wait for 10 seconds before retrying. Next block is called when response object is successfully received and error handler is called when all retries have exhausted. Error provided to the block is the error received on last retry.
In certain cases we do not wish to retry in every case, but in case of bad network connection or certain server state. The code below uses a custom retry block that will retry, if HTTP response status code is 5xx.
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
RACSignal* getSignal = [manager rac_GET:@"http://example.org" parameters:nil retries:3 interval:10.0 test:^BOOL(NSHTTPURLResponse *response, id responseObject, NSError *error)
{
if (response.statusCode >= 500)
{
return YES;
}
else
{
return NO;
}
}];
// Subscribe to signal to start request
[getSignal subscribeNext:^(id responseObject) {
// Handle object
} error:^(NSError *error) {
// Handle error
}];
Dal Rupnik
- legoless on GitHub
- @thelegoless on Twitter
- [email protected]