18

I'm attempting to download a large file on the iPhone and save it to disk as it is downloaded.

Ideally, in:

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {

}

I want to append 'data' to a file on disk.

I've checked out the NSData documentation. There are functions to write to a file, but I can't see anything to append to an existing file.

Does anyone know how I can append this data? Any help much appreciated! Nick.

Nick Cartwright
  • 8,334
  • 15
  • 45
  • 56

2 Answers2

43

You can use a combination of -writeData: and -seekToEndOfFile methods from NSFileHandle class for writing NSData to the end of a file.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • Genius. I swear I looked over the NSFileHandle documentation a few times before writing this post! Must have completely missed these functions! N – Nick Cartwright Aug 10 '09 at 14:51
  • Why not to use NSMutableData? It has appendData: method! – Paresh Masani Feb 20 '12 at 15:23
  • 5
    NSMutableData works in RAM -- downloading a file of any real size will take up your resources. – Vineel Shah Mar 18 '12 at 15:39
  • Yup,Vineel is right.Writing to a file using NSData is convenient but don't use it to write too big a file, or you'll get crashed. – ManuQiao Apr 22 '14 at 06:10
  • And finally check this answer for sample code: http://stackoverflow.com/questions/11106584/appending-to-the-end-of-a-file-with-nsmutablestring – slavik Jul 06 '16 at 07:42
-1

There's a Apple sample app that downloads to a file, using NSOutputStream to write to the file. Look in file "GetController.h" of the sample app called "SimpleURLConnections".

Here's a direct URL -- although I don't think it'll work if you're not logged into to developer.apple.com.

https://developer.apple.com/library/ios/#samplecode/SimpleURLConnections/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009245

Vineel Shah
  • 960
  • 6
  • 14