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];
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.
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);
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With