dispatch_async中的asynchronousurl请求

我试图在一个特定的函数中实现asynchronousurl请求,我想要完成所有这些请求,然后执行一个特定的操作,但该操作先于请求,即在请求完成之前调用它。

dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL); dispatch_async(fetchQ, ^{ [self myAsyncMultipleURLRequestFunction]; dispatch_sync(dispatch_get_main_queue(), ^{ [self updateUIFunction]; }); }); -(void)myAsyncMultipleURLRequestFunction { for (int i=0; i<count; i++) { NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; } } 

现在在myAsyncMultipleURLRequestFunction完成所有请求之前调用updateUIFunction。 也试过这与NSOperaitonQueue,但不能做我真正想要的。

 [_operationQ addOperationWithBlock: ^ { for (int i=0; i<count; i++) { NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; } } [[NSOperationQueue mainQueue] addOperationWithBlock: ^ { // updating UI [self updateUIFunction]; }]; }]; 

我知道这很简单,但我跑outta时间,任何帮助表示赞赏。

@tkanzakic是在正确的道路上。 使用正确的构造是dispatch_group_t。 但是实施可以改进。 通过使用信号量,您可以asynchronous启动所有下载,并确保您没有太多的并发运行。 下面是一个代码示例,说明如何使用dispatch_group_t以及如何使所有下载并行:

 dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL); dispatch_group_t fetchGroup = dispatch_group_create(); // This will allow up to 8 parallel downloads. dispatch_semaphore_t downloadSema = dispatch_semaphore_create(8); // We start ALL our downloads in parallel throttled by the above semaphore. for (int i=0; i<count; i++) { dispatch_group_async(fetchGroup, fetchQ, ^(void) { dispatch_semaphore_wait(downloadSema, DISPATCH_TIME_FOREVER); NSURLConnection *loginConnection = [[NSURLConnection alloc] initWithRequest:requestArray[i] delegate:self]; dispatch_semaphore_signal(downloadSema); }); } // Now we wait until ALL our dispatch_group_async are finished. dispatch_group_wait(fetchGroup, DISPATCH_TIME_FOREVER); // Update your UI dispatch_sync(dispatch_get_main_queue(), ^{ [self updateUIFunction]; }); // Release resources dispatch_release(fetchGroup); dispatch_release(downloadSema); dispatch_release(fetchQ); 

您可以创builddispatch_group_t ,然后使用dispatch_group_notify在组的前一个块完成运行时执行updateUIFunction ,例如:

 dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL); dispatch_async(fetchQ, ^{ dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ [self myAsyncMultipleURLRequestFunction]; }); dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ [self updateUIFunction]; }); }); }); 

首先configuration运行循环。

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [NSURLConnection connectionWithRequest:request delegate:self]; while(!self.finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } }); 

尝试这个