Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 849
Halpo Avatar asked May 27 '16 15:05

Halpo


2 Answers

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.

like image 151
JAL Avatar answered Nov 17 '22 15:11

JAL


In some case you need to set the header for the request, just set requestSerializer using requestSerializer setValue: forHTTPHeaderField: as bellow :

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[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);
}];
like image 1
raed Avatar answered Nov 17 '22 13:11

raed