Downloading a Large File – iPhone SDK

Replace the in-memory NSData *data with an NSOutputStream *stream. In -start create the stream to append and open it:

stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];

As data comes in, write it to the stream:

NSUInteger left = [theData length];
NSUInteger nwr = 0;
do {
    nwr = [stream write:[theData bytes] maxLength:left];
    if (-1 == nwr) break;
    left -= nwr;
} while (left > 0);
if (left) {
    NSLog(@"stream error: %@", [stream streamError]);
}

When you’re done, close the stream:

[stream close];

A better approach would be to add the stream in addition to the data ivar, set the helper as the stream’s delegate, buffer incoming data in the data ivar, then dump the data ivar’s contents to the helper whenever the stream sends the helper its space-available event and clear it out of the data ivar.

Leave a Comment