Changing playerItem of AVPlayer in UITableView

前端 未结 3 1881
我寻月下人不归
我寻月下人不归 2020-12-23 19:47

I have a UITableView containing a number of videos to play when scrolling. As the cells in the tableView are being re-used, I only instantiate one AVPlaye

3条回答
  •  天命终不由人
    2020-12-23 20:33

    In your CustomCell.m you should use thumbnails to display an image for the specific cell video, you could add the thumbnail to a button inside your cell, then build a custom delegate in CustomCell.h that will be called when you tap on the newly created button something like:

    @class CustomCell;
    
    @protocol CustomCellDelegate 
    
    - (void)userTappedPlayButtonOnCell:(CustomCell *)cell;
    
    @end
    

    also in your your .h add the action for the button:

    @interface CustomCell : UITableViewCell
    
    @property (strong, nonatomic) IBOutlet UIButton *playVideoButton;
    
     - (IBAction)didTappedPlayVideo;
     - (void)settupVideoWithURL:(NSString *)stringURL;
     - (void)removeVideoAndShowPlaceholderImage:(UIImage *)placeholder;
    
    @end
    

    also in "didTappedPlayVideo" you do the next:

    - (void)didTappedPlayVideo{
    
    [self.delegate userTappedPlayButtonOnCell:self];
    
    }
    

    the method: settupVideoWithURL is used to init you player and the method: removeVideoAndShowPlaceholderImagewill stop the video and make the AVPlayerItem and AVPlayer nil.

    Now when the user taps a cell you send the call back to the UIViewController where you have the tableView, and in the delegate method you should do the next:

        - (void)userTappedPlayButtonOnCell:(CustomCell *)cell{
    
        //check if this is the first time when the user plays a video
        if(self.previousPlayedVideoIndexPath){
              CustomCell *previousCell = (CustomCell *)[tableView cellForRowAtIndexPath:self.previousPlayedVideoIndexPath];
              [previousCell removeVideoAndShowPlaceholderImage: [UIImage imageNamed:@"img.png"]];
        }
        [cell settupVideoWithURL:@"YOURvideoURL"];
        self.previousPlayedVideoIndexPath = cell.indexPath;
        }
    

    P.S.:

    On older devices(almost all of them until the new iPad Pro) is not indicated to have multiple instances of AVPlayer. Also hope that this chunks of code can guide or help you in your quest :)

提交回复
热议问题