Search code examples
objective-cuitableviewavplayeravkit

How to Play Video from Within Collapsible UITableViewCell?


HI All: I have set up collapsible uitableviewcells and am trying to get video to play in the didSelectRowAtIndexPath method. I can get cells to fire a print statement to the console, but no matter what I try to get a video to play nothing works! Here is the code:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if(indexPath.section == 0)
    {
        if(indexPath.row == 0)
        {
            printf("hello");
        }
        else
        {
        printf("good bye");
        }
    }
    else if(indexPath.section == 1)
    {
        if(indexPath.row == 0)
        {
            printf("hello");
        }
        else
        {
            printf("good bye again");
        }
    }
}

Can you please let me know what I need to do to get a local video file to play? Obviously I need help in Objective C please! I have tried to programmatically create an AVPlayerViewController and then use [self presentviewcontroller] method but I always get the following error (which is same error if I use prepareforSegue):

  NSString *path = [[NSBundle mainBundle] pathForResource:@"PrelimFig1" ofType:@"m4v"];
        _videoURL = [NSURL fileURLWithPath:path];
        NSLog(@"I want to log: %@", _videoURL);
        AVPlayerViewController *avp = [[AVPlayerViewController alloc]init];
        AVPlayer *player = [AVPlayer playerWithURL:_videoURL];
        avp.player = player;

        [self presentViewController:avp animated:YES completion:nil]
        [player play];

Thank you in advance for your help!


Solution

  • You can do like that

       NSURL *videoURLLocal = [[NSBundle mainBundle]URLForResource:@"PrelimFig1" withExtension:@"m4v"];
    
    
        AVPlayerViewController *avp = [[AVPlayerViewController alloc]init];
        AVPlayer *player = [AVPlayer playerWithURL:videoURLLocal];
        avp.player = player;
        [self presentViewController:avp animated:YES completion:^{
            [player play];
        }];
    

    or

           NSURL *videoURLLocal = [[NSBundle mainBundle]URLForResource:@"PrelimFig1" withExtension:@"m4v"];
    
        // create an AVPlayer
        AVPlayer *player = [AVPlayer playerWithURL:videoURLLocal];
    
        // create a player view controller
        AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
        controller.player = player;
        [player play];
    
        // show the view controller
        [self addChildViewController:controller];
        [self.view addSubview:controller.view];
        controller.view.frame = self.view.frame;