Cancel Post request in Afnetworking 2.0
POST
method return the AFHTTPRequestOperation
operation. You can cancel it by calling cancel
.
AFHTTPRequestOperation *post =[manager POST:nil parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//doing something
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// error handling.
}];
//Cancel operation
[post cancel];
How to immediately force cancel an NSOperation with AFNetworking?
After a full morning of digging through AFNetworking source code, it turns out that the reason my operations weren't canceling had nothing to do with the operations themselves, but rather because I've been starting the operations incorrectly all this time. I've been using
[NSOperation start];
when I should have been adding it to my HTTPRequestSingleton
's operation queue:
[[[HTTPRequestSingleton sharedClient] operationQueue] addOperation:NSOperation];
Adding it to the queue allows it to be canceled properly without having to check the isCancelled
property.
AFHTTPRequestOperation Cancel Request
You can use:
[operation cancel];
This is an NSOperation method that's implemented by AFNetworking.
AFNetworking 2: How to cancel a AFHTTPRequestOperationManager request?
Objective-C
[manager.operationQueue cancelAllOperations];
Swift
manager.operationQueue.cancelAllOperations()
How can I migrate in AFNetworking 3.0?
NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[httpClient postPath:@"/myobject" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
afnetworking 3.0 Migration: how to POST with headers and HTTP Body
I was able to figure this out myself.
Here's the solution.
First, you need to create the NSMutableURLRequest
from AFJSONRequestSerializer
first where you can set the method type to POST.
On this request, you get to setHTTPBody
after you have set your HTTPHeaderFields
. Make sure to set the body after you have set the Header fields for content-type, or else the api will give a 400 error.
Then on the manager create a dataTaskWithRequest
using the above NSMutableURLRequest
. Don't forget to resume
the dataTask at the very end or else nothing will get sent yet. Here's my solution code, hopefully someone gets to use this successfully:
NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
}] resume];
How to cancel network request with afnetworking
[[httpClient operationQueue] cancelAllOperations];
AFNetworking 3.0 migration for redirect block
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.
Related Topics
iPhone - Memory Leak - Nsdata Datawithcontentsofurl & UIwebview
Swift 4.2 Make Bottom of Tableview Move Up When Keyboard Shows
How to Enable/Disable Onetimecode Feature for Specific Text Field
How to Use @Objc Protocol with Optional and Extensions at the Same Time
Determine The Maximum Number of Characters a UIlabel Can Take
How to Detect If My Device Is an iPhone x in Swift 4
Fastlane Boarding with Two-Factor Authentication
How to Draw a Uilabel with a Different Blend Mode in Draw(_ Rect: Cgrect) in Swift
Swiftui: Error in Dragging Logic or Is This a Bug
Contentview with UItableview Not Scrolling Within UIscrollview
Filemanager and Urlsfordirectory Error in Swift 3 Xcode 8
How to Access All Images in a .Xcassets at Once
Ar Refernce Image Plane Was Not Position Properly in iOS Swift
Xcode UI Tests Can't Find Views That Are Added Programmatically
Media_Err_Decode on HTML5 Video in iOS UIwebview After Many Plays