Halpo Halpo - 1 year ago 366
iOS Question

AFNetworking 3.0 migration for redirect block

How can I update this deprecated function to use AFNetworking 3.0?

AFHTTPRequestOperation *requestOperation=[[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_URLString]]];
[requestOperation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {
if (redirectResponse) {
//this is the redirected url
return request;
[requestOperation start];

Answer Source

Use setTaskWillPerformHTTPRedirectionBlock on AFHTTPSessionManager. The block set will be called if the initial URL request redirects. You have the option to follow the redirect, or stop the redirect in the block.

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
    NSLog(@"%@", request.URL);
    // This will be called if the URL redirects
    return request; // return request to follow the redirect, or return nil to stop the redirect
[manager GET:_URLString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);

I would recommend you read through the AFNetworking 3.0 Migration Guide.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download