How to cancel an asynchronous http request in Objective-C?

I am trying to add the ability to cancel all current asynchronous requests when the user leaves the view or when initiating a new request. I know where to put the code, but I'm not quite sure how to cancel the request. From my research, I know what the NSURLConnectionmethod has cancel, but I call my requests using asynchronous blocks. Below is my code - any help is greatly appreciated!

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:[kEndpointEvents stringByAppendingString:arguments]]];

//Send an asynchronous request so it doesn't pause the main thread
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    NSHTTPURLResponse *responseCode = (NSHTTPURLResponse *)response;

    //Do stuff

}];
+4
source share
1 answer

Cannot cancel current request using convenient methods +sendAsynchronousRequest:queue:completionHandleror +sendSynchronousRequest:returningResponse:error:.

, NSURLConnectionDataDelegate . , -cancel.

+1

Source: https://habr.com/ru/post/1548716/


All Articles