Halpo Halpo - 4 months ago 139
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
NSLog(@"%@",request.URL);
}
return request;
}];
[requestOperation start];

JAL JAL
Answer

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.