NSURLSesionDataTask取消操作

时间:2014-05-29 09:36:00

标签: iphone objective-c xcode networking nsurlsession

我正在使用NSURLSessionDataTask启动网络服务。这是我的示例代码

NSURLSessionConfiguration *configuration= [XPURLSessionConfiguration setSessionConfiguration:config withAccessability:YES];

 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",self.baseURL,resourceURL]];
        NSLog(@"URL is %@",url);
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];

        NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&eaerror];
        [request setHTTPBody:postData];

        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (!error) {
                NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
                if (httpResp.statusCode == 200) {

                    NSError *jsonError;
                    NSDictionary *notesJSON = [NSJSONSerialization JSONObjectWithData:data
                                                                              options:NSJSONReadingAllowFragments
                                                                                error:&jsonError];

                    NSLog(@"%@",notesJSON);
                    if (!jsonError)
                    {
                        success(notesJSON);
                    }
                    else
                    {
                        failure(jsonError);
                    }
                }
                else{
                    failure([NSError errorWithDomain:@"Title" code:httpResp.statusCode userInfo:nil]);
                }
            }
            else{

                    failure(error);

            }
        }];
        [taskArray addObject:postDataTask];
        [postDataTask resume];

在上面的代码中,我将postDataTask添加到一个数组中,我用它来取消所有操作。

这是我的取消操作。

for (NSURLSessionTask *task in taskArray) {
        if([task state] == NSURLSessionTaskStateRunning){
            [task cancel];
        }
    }

我不确定取消所有操作。什么是取消所有操作的正确方法。当我尝试取消操作时,失败块(即)失败(错误)没有返回。

0 个答案:

没有答案