您可以使用NSBlockOperation
并NSOperationQueue
创建可取消的下载任务。你NSBlockOperation
通过给它一个执行一些工作的块来创建一个。在您的情况下,该块将下载 URL 的内容。
在您的视图控制器中,您将存储已提交到队列的操作列表。如果用户决定离开当前视图,您可以调用cancel
每个挂起的操作以防止发生任何不必要的工作。但是,当前正在运行的操作将运行完成。为了取消当前正在运行的操作,您需要在执行工作的块中存储对 NSOperation 对象的弱引用。然后在块体内的适当时间间隔,您可以检查操作是否已被取消并提前退出。
// Create a queue on which to run the downloads
NSOperationQueue* queue = [NSOperationQueue new];
// Create an operation without any work to do
NSBlockOperation* downloadImageOperation = [NSBlockOperation new];
// Make a weak reference to the operation. This is used to check if the operation
// has been cancelled from within the block
__weak NSBlockOperation* operation = downloadImageOperation;
// The url from which to download the image
NSURL* imageURL = [NSURL URLWithString:@"http://www.someaddress.com/image.png"];
// Give the operation some work to do
[downloadImageOperation addExecutionBlock: ^() {
// Download the image
NSData* imageData = [NSData dataWithContentsOfURL:imageURL];
// Make sure the operation was not cancelled whilst the download was in progress
if (operation.isCancelled) {
return;
}
// Do something with the image
}];
// Schedule the download by adding the download operation to the queue
[queue addOperation:imageDownloadOperation];
// As necessary
// Cancel the operation if it is not already running
[imageDownloadOperation cancel];
今年在 WWDC 上就这个主题进行了一次很好的演讲,题为“在 iOS 上构建并发用户界面”。你可以在这里找到视频和幻灯片