Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You have to wait until the connection tells you it has finished before you can write the data. The connection is handled on another thread; if you try to access the data immediately on the original thread as you're doing, there won't be anything in it.</p> <p>You should move the <code>writeToFile:</code> call to the end of <code>connectionDidFinishLoading:</code>, or to another method that you call from there. That's the first point where you know that the data has all been collected. </p> <p>I'd also suggest creating the <code>NSMutableData</code> instance in <code>didRecieveResponse:</code>, so that you know that it is available at the correct time. That will be more readable/understandable. You can think of the delegate methods as a collective "scope" -- the data is only used inside of them, so it should be created inside of one of them.</p> <p>In reply to your comment:</p> <p>One possibility, since you have so much that needs to be done around this one download, and don't seem to be touching the GUI, is to run the whole <code>parsingComplete:</code> method on a background thread, and using <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html#//apple_ref/doc/uid/20001697-BAJHAHGI" rel="nofollow"><code>+[NSURLConnection sendSynchronousRequest:returningResponse:error:]</code></a>. This way your code will just wait until the data comes back, in one piece, and you can write it immediately after the <code>sendSynchronous...</code> call returns.</p> <pre><code>NSError * err; NSURLResponse * response; NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:&amp;response error:&amp;err]; if( !receivedData ){ /* Handle error */ } /* Check response */ BOOL result = [receivedData writeToFile:fileOut atomically:YES]; /* check result, etc. */ </code></pre>
 

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