我已设置连接以将this mp4 clip下载到我的设备,并且我使用以下委托功能以“流式”方式存储数据。
- (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];
}
然而,当5.3MB文件下载完毕后,我检查保存文件的大小,它只有1KB,因此无法播放。我只是保存一小块而不是像我想要的那样吗?我需要做些什么不同的事情?
答案 0 :(得分:2)
您需要在收到数据时连接数据。查看NSMutableData对象。数据完成后,将逻辑放入connectionDidFinishLoading委托方法中。
使用此示例,其中receivedData是您在开始下载之前初始化的属性。
- (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];
}
答案 1 :(得分:2)
上面的答案会在下载时将整个视频保留在内存中。虽然这对于小视频来说可能很好,但这不适用于较大的视频。您可以将数据附加到本地驱动器上的文件中,如下所示:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.path];
[handle seekToEndOfFile];
[handle writeData:data];
}