近日在做一个基于MPMoviePlayerViewController播放m3u8格式的广播APP时候,引发一个全球的搜索,在简单的代码播放测试成功后,
player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
做了播放状态的监测,代码如下:
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(moviePlayerPreloadDidFinish:)
name:
MPMediaPlaybackIsPreparedToPlayDidChangeNotification
object:player];
可以从接口API文件中找到这个已经加载成功后的通知,非常简单即可完成,但是根据程序员的0 1 思想,有成功,必然要有失败,于是让手机处于飞行模式,于是检测到爆出错误:
_itemFailedToPlayToEnd: { kind = 1; new = 2; old = 0; }
但是找遍系统API也没有找到一个监测到失败加载的通知,于是开始有目的的Google和百度,甚至stackoverflow,但是都是疑问和我类似,始终没有发现解决方案,最后终于在一个角落找到一个解决方案,根据代码测试,发现非常靠谱,代码如下:
首先,设置通知监听:
[notificationCenter addObserver:self
selector:@selector(videoHasFinishedPlaying:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
然后在监听回调函数中做如下判断:
- (void)videoHasFinishedPlaying:(NSNotification *)paramNotification{
/* Find out what the reason was for the player to stop */
NSNumber *reason =
[paramNotification.userInfo
valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if (reason != nil){
NSInteger reasonAsInteger = [reason integerValue];
switch (reasonAsInteger){
case MPMovieFinishReasonPlaybackEnded:{
/* The movie ended normally */
break; }
case MPMovieFinishReasonPlaybackError:{
/* An error happened and the movie ended */
break;
}
case MPMovieFinishReasonUserExited:{
/* The user exited the player */
break;
}
}
NSLog(@"Finish Reason = %ld", (long)reasonAsInteger);
} /* if (reason != nil){ */
}
通过以上判断即可得到加载失败的原因,可以处理 _itemFailedToPlayToEnd: { kind = 1; new = 2; old = 0; } 这种错误信息,最后根据自己的需要完成用户提示等功能,至此实现了 0 1 功能。
附:个人开发者 -微推官网:http://www.micropush.cn/