如何发出异步可变请求并仅获取最后一个请求值并取消最后一个请求之前的所有请求

how to make asynchronous Mutable request and getting only last request value and canceling all request before last request

NSError *error   = nil;


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSOperationQueue *downloadOperationQueue = [[NSOperationQueue alloc] init];
[downloadOperationQueue cancelAllOperations];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:Url]];


[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSLog(@"Respose %@",response.URL);
     NSString *jsonInString = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
     NSLog(@"json in string for backend: %@",jsonInString);

     [self.delegate responseConnection:data withMethodName:methodName];
     if (!error)
     {
         // did finish logic here, then tell the caller you are done with success
         // completion(YES, nil);
     }
     else
     {
         // otherwise, you are done with an error
         //  completion(NO, error);
     }
 }];

对于NSURLSession

您可以使用[NSURLSession cancelPreviousPerformRequestsWithTarget:self];

对于NSURLConnection

您可以使用[NSURLConnection cancelPreviousPerformRequestsWithTarget:self];