0

I have set up a connection to download this mp4 clip to my device and I'm using the following delegate function to store the data in a "streaming" type fashion.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"BuckBunny.mp4"];

    [data writeToFile:filePath atomically:YES];
}

However, when the 5.3MB file is finished downloading, I check the size of the saved file and it's only 1KB and consequently won't play. Am I just saving a small slice instead of the whole thing like I wanted? What do I need to do differently?

Jacksonkr
  • 29,242
  • 36
  • 164
  • 265

2 Answers2

2

You need to concatenate the data as you receive it. Look at the NSMutableData object. Once the data is complete, put logic to proceed in the connectionDidFinishLoading delegate method.

Use this example, where receivedData is a property that you init before you begin the download.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"BuckBunny.mp4"];

    [receivedData writeToFile:filePath atomically:YES];
    [connection release];
}
Ben M
  • 2,145
  • 17
  • 17
2

The answer above will keep your entire video in memory while it is downloading. While this is probably fine for a small video, this could not be used for larger videos. You can append the data to the file on the local drive like this:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.path];
    [handle seekToEndOfFile];
    [handle writeData:data];
}
lehn0058
  • 19,077
  • 14
  • 65
  • 107