0

我创建了一个 iCarousel 视图,并尝试在每个“单元格”/视图中显示视频预览。

我将视频存储在 Parse 中,并且正在尝试

  1. 从云端查询
  2. 从 PFFile 中检索数据
  3. 将数据转换为 URL
  4. 使用 AVPlayer 播放 URL

到目前为止,这是我的代码。

-(void)getPast{
dataArray = [[NSMutableArray alloc]init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
PFQuery *query = [PFQuery queryWithClassName:@"History"];
[query whereKey:@"Location" containsString:[defaults objectForKey:@"location"]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    pastArray = [NSMutableArray arrayWithArray:objects];
    for (PFObject *files in objects){
        PFFile *file = [files objectForKey:@"File"];
        [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {

            [dataArray addObject:data];

        }];
    }
    [self.carouselView reloadData];
}];
}

我收到一个错误,说我的 dataArray 是空的,我认为这里的问题可能是因为我在后台查询,所以 For 循环在我收到数据之前完成,因此数组是空的,尽管我可能是错了,即使我是对的,我也不知道如何解决这个问题。

显示预览的代码

 - (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {



        PFObject *object = [pastArray objectAtIndex:index];
        NSData *data = [dataArray objectAtIndex:index];
        NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSURL *URL = [NSURL URLWithString:dataString];
        NSLog(@"URL %@",URL);
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 275)];
        self.playerViewController = [[AVPlayerViewController alloc]init];
    self.playerViewController.player = [AVPlayer playerWithURL:URL];
    self.playerViewController.view.frame = view.bounds;
    self.playerViewController.showsPlaybackControls = NO;


    [view addSubview:self.playerViewController.view];
    view.autoresizesSubviews = YES;

    self.playerViewController.player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerViewController.player.currentItem];
    [self.playerViewController.player play];



    return view;


    }

如何修复我的代码,以便每个视图自动播放与其在数组中的索引相对应的 PFFile 视频。

我的问题:数组为空

无法为每个视图播放内容

附言。我知道我没有使用 PFObject *object。

4

1 回答 1

0

正如您猜测的那样,for循环在调用块之前完成了它的执行方式,您必须确保在调用 reloadData 之前加载数据

关于如何处理这个问题,我首先想到的是

for (PFObject *files in objects){
    PFFile *file = [files objectForKey:@"File"];
    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error)   {

        [dataArray addObject:data];
        [self checkData];
    }];
} 


- (void)checkData {
   //Check the if the data is completed
   if(dataArray.count == numberOfFiles) { //Maybe a more complex if is required here but you get the idea
       //All files are downloaded
       dispatch_async(dispatch_get_main_queue(), ^{
          //We are sure the data is ready so we reload it
          [self.carouselView reloadData];
       });
   }
}

此外,您应该始终在加载之前检查 NSData 是否有效

于 2015-12-16T21:59:09.903 回答