cancel NSURLConnection in ios

与世无争的帅哥 提交于 2019-12-18 09:34:12

问题


I am calling webservice on mapView drag/regionChange. I want to keep some delay in the web service calls. So I want that whenever the user drags the map multiple times, all previous web service calls should be cancelled and only last drag web service call should be fired.

How do I do this?

Following is my code:

{ .... NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[data length]];

        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:data];

        [request setHTTPMethod:@"POST"];
        NSMutableDictionary __block *dictResponse;
    [[NSOperationQueue mainQueue] cancelAllOperations];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

            if(connectionError == nil){

                dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
                }

回答1:


You cannot cancel a sendAsynchronousRequest. If you used a delegate-based NSURLConnection request, then you could cancel it, but (a) that's more coding than you probably want to bother with; (b) NSURLConnection is deprecated, so you should be NSURLSession anyway; and (c) NSURLSession allows you to cancel the task using the NSURLSessionTask reference that is returned to you:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"connection error = %@", error);
        return;
    }
    NSError *parseError;
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
    if (!responseObject) {
        NSLog(@"parse error = %@", parseError);
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        // use response here; e.g., updating UI or model objects
    });
}];
[task resume];

If you need to cancel this request, just call [task cancel]. So save this NSURLSessionTask in some weak variable if you want to keep track of it and cancel it later.




回答2:


Don't use the sendAsynchronousRequest convenience API, use the main delegate API so you have access to the instance of NSURLConnecyion to call cancel on.

Also, don't cancel operations on the main queue, you don't know what's there, and consider using NSURLSession



来源:https://stackoverflow.com/questions/33315590/cancel-nsurlconnection-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!