试试这个
我开始使用 NSURLConnection 下载视频文件
然后我实现接收到的数据委托方法,如下所示。
- (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)aData
{
bytesFetched += aData.length;
if( bytesFetched > kBytesRequiredBeforeStart && !hasCachedData ) // kBytesRequiredBeforeStart = 160000
{
[[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheHasDataNotification object:self];
hasCachedData = YES;
}
[self.fileHandle writeData:aData]; // this file handle is not closed until after the video has finished downloading
}
fileHandle 是这样创建的
- (NSFileHandle *)fileHandle
{
if( fileHandle == nil )
{
NSError * theError = nil;
cachedURL = [[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingFormat:@"/%@", kTempFileName]] retain];
[[NSFileManager defaultManager] createFileAtPath:[self.cachedURL path] contents:nil attributes:nil];
fileHandle = [[NSFileHandle fileHandleForWritingToURL:self.cachedURL error:&theError] retain];
if( fileHandle == nil )
[[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheErrorOccuredNotification object:self];
}
return fileHandle;
}
*我也有类似这样的完成委托处理方法*
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if( hasCachedData == NO )
{
[[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheHasDataNotification object:self];
hasCachedData = YES;
}
hasFinishedCaching = YES;
[[NSNotificationCenter defaultCenter] postNotificationName:kVideoURLCacheDidFinishLoadingNotification object:self];
}
然后我有一个方法来观察通知,如下所示
- (void)videoURLCacheHasDataNotification:(NSNotification *)aNotification
{
[self.videoController play];
}
videoController 是如下创建的 MPMoviePlayerController 的一个实例,cachedURL 与上面定义的相同。
- (MPMoviePlayerController *)videoController
{
if( videoController == nil )
{
NSURL * theURL = self.videoURLCache.cachedURL;
NSLog( @"Video URL = '%@'", theURL );
videoController = [[MPMoviePlayerController alloc] initWithContentURL:theURL];
videoController.shouldAutoplay = NO;
[videoController setFullscreen:NO animated:NO];
videoController.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleHeight;
videoController.repeatMode = MPMovieRepeatModeOne;
videoController.controlStyle = MPMovieControlStyleEmbedded;
videoController.view.frame = self.videoView.bounds;
[videoView addSubview:self.videoController.view];
}
NSParameterAssert(videoController != nil);
return videoController;
}