How to get an error description when playback fails on MPMoviePlayerController

前端 未结 3 1985
一整个雨季
一整个雨季 2020-12-10 05:01

I want to show an UIAlert if the Video-Play fails. So i registered the MPMoviePlayerPlaybackDidFinishNotification for my Movie Player:

3条回答
  •  渐次进展
    2020-12-10 05:43

    Unfortunately, MPMoviePlayerController (up until but not including iOS 4.3) has no verbose identification of problems from what is available from the documentation. It simply returns MPMovieFinishReasonPlaybackError in case of any problem within the UserInfo of that MPMoviePlayerPlaybackDidFinishNotification.

    With iOS 4.3 we finally got the errorLog and accessLog properties containing extended and pretty helpful information. See MPMoviePlayerController Reference.

    With iOS 5.0 there is an error key coming with that notification also on device builds and not just within the simulator. That error is an instance of NSError and supplies very helpful information. Unfortunately that has not been documented by Apple, hence it may change at any release of iOS. Additionally, there seems to be no explanation on the given error-codes. For example an HTTP-Status:404 would result into an error-code -1100 within the given error instance. However, this would be an example of how to handle this notification in the most proper way.

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(handleMPMoviePlayerPlaybackDidFinish:)
                                                name:MPMoviePlayerPlaybackDidFinishNotification
                                              object:nil];
    

    That would be a proper notification handler:

    - (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");
            }
        }
    }
    

    Last but not least, do not forget to remove that notification handler from the default center when releasing the instance of the object you are handling it within.

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:nil];
    

提交回复
热议问题