当前位置: 动力学知识库 > 问答 > 编程问答 >

nsurlconnection - ios problems with downloading an mp4 file

问题描述:

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?

网友答案:

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];
}
网友答案:

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];
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: