Search code examples
iosobjective-cvideompmovieplayercontroller

iOS video not playing with MPMoviePlayer


I'am making video player module for my app.

This is my .h file:

#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>

@interface SpanishViewController : UIViewController
- (IBAction)Video1Button:(id)sender;

@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;


@end

This is code of event executed by button in .m file:

- (IBAction)Video1Button:(id)sender {

    NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"01" ofType:@"mp4"];
    NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];
    MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlaybackComplete:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:moviePlayerController];

    [self.view addSubview:moviePlayerController.view];
    moviePlayerController.fullscreen = YES;

    [moviePlayerController play];
}

Video encoded in mp4 in accordance with the standards and runs on iOS. Result is - here

Video does not start, the button "Done" does not work .. I can not understand what went wrong. Please help me.


Solution

  • Yes, the problem is, instead of using global property

    @property (nonatomic, strong) MPMoviePlayerController *moviePlayer;

    you have re-declared a MPMoviePlayerController in your - (IBAction)Video1Button:(id)sender; method.

    Because of that, life of the moviePlayer ends with the end of Video1Button method.

    correct way,

    - (IBAction)Video1Button:(id)sender {
    
        NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"01" ofType:@"mp4"];
        NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];
        _moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
    
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(moviePlaybackComplete:)
                                                     name:MPMoviePlayerPlaybackDidFinishNotification
                                                   object:self.moviePlayerController];
    
        [self.view addSubview:_moviePlayerController.view];
        _moviePlayerController.fullscreen = YES;
    
        [_moviePlayerController play];
    }