如何管理AFNetworking请求编号?

时间:2012-10-26 04:09:01

标签: ios grand-central-dispatch afnetworking

在我的iOS应用程序中,我有数百个图像下载。

我使用AFNetworking来获取这些图像。我想管理AFWorking的请求编号。

这是我的代码:

问题是:它会阻止我的用户界面。

THX求助我!

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(5);

for (NSString *urlString in self.downloadImageList) {
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_group_async(group, queue, ^{
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSString *filename = url.lastPathComponent;
        NSURL *outputFileURL = APPLICATION_DOCUMENTS_DIRECTORY;
        outputFileURL = [outputFileURL URLByAppendingPathComponent:[NSString stringWithFormat:@"%@/images/%@",self.boardId,filename]];

        dispatch_group_async(group, dispatch_get_main_queue(), ^{
            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            operation.outputStream = [NSOutputStream outputStreamWithURL:outputFileURL append:YES];
            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                [self.downloadImageList removeObject:urlString];
                NIDINFO(@"download success %@",filename);
                dispatch_semaphore_signal(semaphore);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NIDERROR(@"download image error:%@\n%@",error,urlString);
                dispatch_semaphore_signal(semaphore);
            }];
            [operation start];
        });

    });
}

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
dispatch_release(group);

1 个答案:

答案 0 :(得分:0)

  

问题是:它会阻止我的用户界面。

好吧,这就是dispatch_semaphore_t的重点。如果删除这些调用,AFNetworking调用将在后台异步执行,而不会影响您的主/ UI线程。

我不知道使用此代码的完整上下文,但看起来您可能要考虑让调用此方法的方法采用块参数,可以在所有请求完成后调用。您可能还想了解AFHTTPClient的批处理操作功能,它允许您跟踪一组操作的进度,为每个操作单独获取回调,以及何时完成。