不幸的是,MPMoviePlayerController
(直到但不包括iOS 4.3)從文檔中沒有詳細的問題識別。如果MPMoviePlayerPlaybackDidFinishNotification
的UserInfo中存在任何問題,它只會返回MPMovieFinishReasonPlaybackError
。
對於iOS 4.3,我們終於獲得了包含擴展且非常有用的信息的errorLog
和accessLog
屬性。 見MPMoviePlayerController Reference。
在iOS 5.0中,有一個error
密鑰隨設備構建而來,而不僅僅是在模擬器中。那error
是NSError
的一個實例,並提供非常有用的信息。不幸的是,這還沒有被蘋果公司記錄下來,因此它可能會在任何iOS版本上發生變化。另外,對於給定的錯誤代碼似乎沒有解釋。例如,HTTP-Status:404將導致給定錯誤實例中的錯誤代碼-1100
。但是,這將是如何以最合適的方式處理此通知的示例。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleMPMoviePlayerPlaybackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
這將是一個適當的通知處理程序:
- (void)handleMPMoviePlayerPlaybackDidFinish:(NSNotification *)notification
{
NSDictionary *notificationUserInfo = [notification userInfo];
NSNumber *resultValue = [notificationUserInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
MPMovieFinishReason reason = [resultValue intValue];
if (reason == MPMovieFinishReasonPlaybackError)
{
NSError *mediaPlayerError = [notificationUserInfo objectForKey:@"error"];
if (mediaPlayerError)
{
NSLog(@"playback failed with error description: %@", [mediaPlayerError localizedDescription]);
}
else
{
NSLog(@"playback failed without any given reason");
}
}
}
最後但並非最不重要的,不要忘記釋放你要處理它的對象的實例時,從默認中心刪除通知處理程序中。
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];
這是可愛的,但它似乎已經壞了。使用iOS 8.1和我的MPMoviePlayer.url得到404錯誤,但它沒有觸發[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackDidFinish :) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; – Lombas 2016-07-12 20:23:40
鑑於蘋果已經棄用MPMoviePlayer,我覺得使用AVFoundation代替它會更安全。 – Till 2016-07-13 20:11:32