Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can make use of <code>NSBlockOperation</code> and <code>NSOperationQueue</code> to create a cancellable download task. You create an <code>NSBlockOperation</code> by giving it a block which performs some work. In your case the block would download the contents of the URL. </p> <p>In your view controller, you would store a list of the operations that have been submitted to the queue. If the user decides to leave the current view, you can then call <code>cancel</code> on each of the pending operations to prevent any needless work from taking place. The currently running operation will run to completion however. In order to cancel the currently running operation, you need to store a weak reference to the NSOperation object in the block doing teh work. Then at appropriate intervals within the body of the block, you can check to see if the operation has been cancelled and exit early.</p> <pre><code>// 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]; </code></pre> <p>A good talk on this exact topic was given at WWDC this year entitled "Building Concurrent User Interfaces on iOS". You can find the video and slides <a href="https://developer.apple.com/videos/wwdc/2012/" rel="nofollow">here</a> </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload