Search code examples
iosiphonexcodeipadmpmovieplayercontroller

Read video file from documents folder


I have this code that works fine and shows me the video in my app:

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"movie" ofType:@"mp4"]];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:playercontroller];
playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playercontroller.moviePlayer play];
playercontroller = nil;

What I need is to read the same file from documents folder, and it exist, so what I did is:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *str = [NSString stringWithFormat:@"%@/MyCoolApp/Animations/%@", documentsPath,@"movie"];
NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:str ofType:@"mp4"]];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:playercontroller];
playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playercontroller.moviePlayer play];
playercontroller = nil;

The file is there, but nothing playing, just loading.


Solution

  • You are getting the path for the documents folder then trying to find it in the main bundle.

    Try the following:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"/MyCoolApp/Animations/movie.mp4"];
    NSURL *movieURL = [NSURL fileURLWithPath:path];
    
    MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
    [self presentMoviePlayerViewControllerAnimated:playercontroller];
    playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [playercontroller.moviePlayer play];
    playercontroller = nil;