Добавление нескольких видео в uicollectionview-objective-c

У меня возникли проблемы с добавлением нескольких видео в uicollectionview.
Я могу добавить несколько изображений в uicollectionview, и они отображаются правильно.
Однако при попытке добавить несколько видео будет воспроизводиться только последнее добавленное видео.

// Выберите изображение / видео из телефонной галереи

- (void)chooseExistingImagesButton:(id)sender {

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, (NSString *)kUTTypeVideo, (NSString*)kUTTypeImage, nil];
    picker.allowsEditing = NO;
    picker.delegate = self;

    [self presentViewController:picker animated:YES completion:nil];
}
else {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"Sorry, we cannot detect a camera on this device." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertView show];
}

[imageCollectionView reloadData];
[videoCollectionView reloadData]; }

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[self targetImageArray];
[self targetVideoArray];

NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
    NSString *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [targetImageArray addObject:selectedImage];
    [targetImageArray componentsJoinedByString:@","];
}
else if (([mediaType isEqualToString:(NSString *)kUTTypeVideo]) || ([mediaType isEqualToString:(NSString *)kUTTypeMovie])) {
    NSString *moviePath = [info objectForKey:UIImagePickerControllerMediaURL];
    [targetVideoArray addObject:moviePath];
    [targetVideoArray componentsJoinedByString:@","];
}

[imageCollectionView reloadData];
[videoCollectionView reloadData];

[self dismissViewControllerAnimated:YES completion:^{NSLog(@"Finished Picking Image or Video");}]; }

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:^{NSLog(@"Image picker view dismissed");}]; }

// Загрузить collectionview

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1; }

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
if (collectionView.tag == ImageCell) {
    return [targetImageArray count];
}
if (collectionView.tag == VideoCell) {
    return [targetVideoArray count];
}
return 0; }

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

if (collectionView.tag == VideoCell) {
    static NSString *videoCellIdentifier = @"VideoCell";
    TargetVideoCell *videoCell = [collectionView dequeueReusableCellWithReuseIdentifier:videoCellIdentifier forIndexPath:indexPath];

    movieUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", [targetVideoArray objectAtIndex:indexPath.row]]];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:movieUrl options:nil];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    UIImage *image = [UIImage imageWithCGImage:[generator copyCGImageAtTime:CMTimeMake(0, 1) actualTime:nil error:nil]];

    videoCell.targetMovieView.image = image;

    [moviePlayer.view setFrame:videoCell.targetMovieView.frame];
    moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];

    return videoCell;
}


if (collectionView.tag == ImageCell) {
    static NSString *imageCellIdentifier = @"ImageCell";
    TargetImageCell *imageCell = [collectionView dequeueReusableCellWithReuseIdentifier:imageCellIdentifier forIndexPath:indexPath];

    imageCell.targetImageView.image = [targetImageArray objectAtIndex:indexPath.row];
    return imageCell;
}

return 0; }

// Воспроизводить видео

- (IBAction)playMovie:(id)sender {
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMovieFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer]; }

- (void)playMovieFinished:(NSNotification *)theNotification {
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
[moviePlayer.view removeFromSuperview];
moviePlayer = nil;
[self dismissMoviePlayerViewControllerAnimated]; }

1 ответ

  1. На каждом cellForRow вы init ваш плеер кино снова. moviePlayer-это свойство вашего класса.

    Решение:

    1. каждая ячейка должна иметь свой видеоплеер.

      videoCell.moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
      [videoCell.moviePlayer.просмотр setFrame: videoCell.targetMovieView.границы];

    2. имеет один игрок кино и улавливая событие выстукивать кнопки