Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A better idea is to download the file asynchronously. This has several advantages: The most important one is that your user interface stays responsive. The user can go on using your application while it is downloading and waiting for the data. If the data you are downloading is absolutely essential for the application, display some sort of loading indicator. </p> <p>You can easily start the asynchronous download via </p> <pre><code>NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:sourceUrl]]; NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; </code></pre> <p>Now, how do I get the downloades data in an <code>NSData</code> object? You implement the following delegate methods for <code>self</code>:</p> <pre><code>-connection:didReceiveData: -connection:didFailWithError: -connectionDidFinishLoading: </code></pre> <p>The idea is that you are notified whenever some data drops in through your connection or anything important else happens (success or failure for exmple). So you are going to declare a temporary <code>NSMutableData</code> object as an instance variable (say <code>downloadData</code>) and write to it until the download is complete. Do not forget to initialize the empty object and declare a property as well!</p> <p><code>-connection:didReceiveData:</code> is called whenever some sort of data (that is, a part of your downloaded file) arrives. So you are going to append it to your temporary object like this:</p> <pre><code>-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.downloadData appendData:data]; } </code></pre> <p>Once the download has finished (successfully), the next delegate method is called:</p> <pre><code>-(void) connectionDidFinishLoading:(NSURLConnection *)connection { //do whatever you need to do with the data in self.downloadData } </code></pre> <p>If the downloads fails, <code>-connection:didFailWithError:</code> is called. You can then save the temporary object, get its size and resume the download later. <code>[self.downloadData length];</code> gets you the size in bytes of the data in your object. </p>
 

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