首页 > 解决方案 > 我正在尝试从 collectionview 中显示的 URL 下载照片列表,但我无法找到执行此操作的方法

问题描述

我需要从服务器获取照片的几个 URL 并将它们显示在 collectionview 中。问题是,他们提供了一个名为“findObjectsInBackgroundWithBlock”的 api,让我从服务器下载 URL。它会在后台自动从服务器下载。我正在尝试使用dispatch_async,但collectionview似乎有一些问题。有任何想法吗?

 BmobQuery *picturesB = [BmobQuery queryWithClassName:@"AssetPicture"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[picturesB findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error)
 {
     for (BmobObject *obj in array)
     {
         [photourl addObject:[obj objectForKey:@"imageUrl"]];
     }
     for (int i = 0; i < 12; i++) {
         NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:photourl[i]]];
         [self.arr addObject:[UIImage imageWithData:imageData]];  
     }     
 }];//Bmob query        


if(self.arr!=nil)
   {
    dispatch_async(dispatch_get_main_queue(), ^{         
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"MyCollectionCell"]; 
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];   
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[CollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Header"];
       });// dispatch
   }//if
  });//dispatch

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

CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCollectionCell" forIndexPath:indexPath];
cell.imageView.image = [self.arr objectAtIndex:indexPath.row];
NSLog(@"photo done");
cell.descLabel.text = [[NSString alloc] initWithFormat:@"{%ld,%ld}",indexPath.section,indexPath.row];
return cell;

}

标签: iosobjective-c

解决方案


推荐阅读