2016-10-24 3 views
0

사진 프레임 워크를 사용하여 UICollectionView를 채 웁니다. 그것은 쉬운 패턴이어야하지만 숨겨진 셀에 대한 요청을 취소하는 데 문제가 있습니다.iOS PHImageManager cancelImageRequest가 작동하지 않습니까?

이것은 몇 가지 예에서 찍은 내 코드입니다 :

#pragma mark - UICollectionView DataSource 
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 
{ 
    return 1; 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return [_photos count]; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    GalleryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath]; 
    NSLog(@">>>>>>SHOWING CELL %d WITH MEMADDRESS %p", indexPath.row, cell); 
    PHAsset *asset = [_photos objectAtIndex:indexPath.row]; 
    PHImageRequestOptions *option = [PHImageRequestOptions new]; 
    option.synchronous = NO; 
    option.version = PHImageRequestOptionsVersionCurrent; 
    option.networkAccessAllowed = YES; 
    option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic; 
    option.resizeMode = PHImageRequestOptionsResizeModeFast; 

    PHImageRequestID requestId = cell.tag; 
    if(requestId != 0) 
    { 
     [_imgManager cancelImageRequest:requestId]; 
     NSLog(@">>>>>>1ST CANCEL CELL %d WITH MEMADDRESS %p AND REQUESTID %d", indexPath.row, cell, requestId); 
    } 
    [cell.photoIV setImage:nil]; 
    cell.tag = [_imgManager requestImageForAsset:asset 
             targetSize:CGSizeMake(CAMERA_GALLERY_SIZE, CAMERA_GALLERY_SIZE) 
       //       contentMode:PHImageContentModeAspectFit 
            contentMode:PHImageContentModeDefault 
             options:option 
            resultHandler:^(UIImage *result, NSDictionary *info) { 
             //if([self isRowVisible:indexPath]) 
             //{ 
             [cell.photoIV setImage:result]; 
             NSLog(@">>>>>>Assigning photo to cell %d with memaddress %p", indexPath.row, cell); 
             //} 
             //else 
             //{ 
             // NSLog(@">>>>>>We should assign photo to cell %d with memaddress %p but this cell is not visible", indexPath.row, cell); 
             //} 
            }]; 
    NSLog(@">>>>>>LOADING CELL %d WITH MEMADDRESS %p AND REQUESTID %d", indexPath.row, cell, requestId); 
    if([_selectedPhotos containsObject:asset]) 
     [cell.selectedIV setHidden:NO]; 
    else 
     [cell.selectedIV setHidden:YES]; 
    [cell.isMineIV setHidden:YES]; 

    return cell; 
} 

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSLog(@">>>>>>HIDDING CELL %d WITH MEMADDRESS %p", indexPath.row, cell); 
    [((GalleryViewCell *)cell).photoIV setImage:nil]; 
    PHImageRequestID requestId = cell.tag; 
    if(requestId != 0) 
    { 
     [_imgManager cancelImageRequest:requestId]; 
     NSLog(@">>>>>>2ND CANCEL CELL %d WITH MEMADDRESS %p AND REQUESTID %d", indexPath.row, cell, requestId); 
    } 
} 

-(BOOL) isRowVisible:(NSIndexPath *) indexPath 
{ 
    NSArray *indexes = [_photosCV indexPathsForVisibleItems]; 
    for (NSIndexPath *index in indexes) 
    { 
     if (index.row == indexPath.row) 
     { 
      return YES; 
     } 
    } 

    return NO; 
} 

글쎄, 나는 각 셀을 새로 고칠 여러 번, 2 또는 3 개 이미지의를 보여주는 아래까지 컬렉션보기에서 빠른 스크롤을 할 경우 1 초 또는 2 초. 셀이 더 이상 보이지 않거나 셀이 다시 표시 될 때 같은 셀의 이전 요청을 취소하려고했지만 결과를보고 로그를 보면 요청이 취소되지 않는 것으로 보입니다.

아래 목록을 스크롤 한 다음 내 목록 맨 위로 스크롤 한 다음 내 기록입니다.

2016-10-24 22:10:46.284 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 17 WITH MEMADDRESS 0x17351660 
2016-10-24 22:10:46.286 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 17 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 
2016-10-24 22:10:46.288 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 15 WITH MEMADDRESS 0x1736a890 
2016-10-24 22:10:46.289 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 15 WITH MEMADDRESS 0x1736a890 AND REQUESTID 349 
2016-10-24 22:10:46.291 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 0 WITH MEMADDRESS 0x1736a890 
2016-10-24 22:10:46.291 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 0 WITH MEMADDRESS 0x1736a890 AND REQUESTID 349 
2016-10-24 22:10:46.293 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 0 with memaddress 0x1736a890 
2016-10-24 22:10:46.293 Fotoloop[9834:4281410] >>>>>>LOADING CELL 0 WITH MEMADDRESS 0x1736a890 AND REQUESTID 349 
2016-10-24 22:10:46.298 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 1 WITH MEMADDRESS 0x17351660 
2016-10-24 22:10:46.298 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 1 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 
2016-10-24 22:10:46.301 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 1 with memaddress 0x17351660 
2016-10-24 22:10:46.303 Fotoloop[9834:4281410] >>>>>>LOADING CELL 1 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 
2016-10-24 22:10:46.310 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 2 WITH MEMADDRESS 0x1744d350 
2016-10-24 22:10:46.311 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 2 WITH MEMADDRESS 0x1744d350 AND REQUESTID 350 
2016-10-24 22:10:46.312 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 2 with memaddress 0x1744d350 
2016-10-24 22:10:46.312 Fotoloop[9834:4281410] >>>>>>LOADING CELL 2 WITH MEMADDRESS 0x1744d350 AND REQUESTID 350 
2016-10-24 22:10:46.316 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 3 WITH MEMADDRESS 0x171c0fd0 
2016-10-24 22:10:46.317 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 3 WITH MEMADDRESS 0x171c0fd0 AND REQUESTID 348 
2016-10-24 22:10:46.318 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 3 with memaddress 0x171c0fd0 
2016-10-24 22:10:46.318 Fotoloop[9834:4281410] >>>>>>LOADING CELL 3 WITH MEMADDRESS 0x171c0fd0 AND REQUESTID 348 
2016-10-24 22:10:46.325 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 4 WITH MEMADDRESS 0x15f15b60 
2016-10-24 22:10:46.339 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 4 WITH MEMADDRESS 0x15f15b60 AND REQUESTID 347 
2016-10-24 22:10:46.363 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 4 with memaddress 0x15f15b60 
2016-10-24 22:10:46.365 Fotoloop[9834:4281410] >>>>>>LOADING CELL 4 WITH MEMADDRESS 0x15f15b60 AND REQUESTID 347 
2016-10-24 22:10:46.371 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 5 WITH MEMADDRESS 0x1710b1b0 
2016-10-24 22:10:46.373 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 5 WITH MEMADDRESS 0x1710b1b0 AND REQUESTID 346 
2016-10-24 22:10:46.376 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 5 with memaddress 0x1710b1b0 
2016-10-24 22:10:46.377 Fotoloop[9834:4281410] >>>>>>LOADING CELL 5 WITH MEMADDRESS 0x1710b1b0 AND REQUESTID 346 
2016-10-24 22:10:46.399 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 23 with memaddress 0x171d3600 
2016-10-24 22:10:46.401 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 16 with memaddress 0x1744d350 
2016-10-24 22:10:46.408 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 12 WITH MEMADDRESS 0x15feda90 
2016-10-24 22:10:46.408 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 12 WITH MEMADDRESS 0x15feda90 AND REQUESTID 352 
2016-10-24 22:10:46.409 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 13 WITH MEMADDRESS 0x171d7d00 
2016-10-24 22:10:46.409 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 13 WITH MEMADDRESS 0x171d7d00 AND REQUESTID 353 
2016-10-24 22:10:46.410 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 14 WITH MEMADDRESS 0x171ef8d0 
2016-10-24 22:10:46.410 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 14 WITH MEMADDRESS 0x171ef8d0 AND REQUESTID 354 
2016-10-24 22:10:46.430 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 19 with memaddress 0x15f15b60 
2016-10-24 22:10:46.490 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 15 with memaddress 0x1736a890 
2016-10-24 22:10:46.504 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 0 with memaddress 0x1736a890 
2016-10-24 22:10:46.551 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 17 with memaddress 0x17351660 
2016-10-24 22:10:46.614 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 13 with memaddress 0x171d7d00 
2016-10-24 22:10:46.677 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 9 with memaddress 0x1735b730 
2016-10-24 22:10:46.743 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 12 with memaddress 0x15feda90 
2016-10-24 22:10:46.808 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 10 with memaddress 0x171e3660 
2016-10-24 22:10:46.865 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 14 with memaddress 0x171ef8d0 
2016-10-24 22:10:46.927 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 11 with memaddress 0x15f27020 
2016-10-24 22:10:46.996 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 6 with memaddress 0x171d3600 
2016-10-24 22:10:47.053 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 7 with memaddress 0x17133010 
2016-10-24 22:10:47.088 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 3 with memaddress 0x171c0fd0 
2016-10-24 22:10:47.114 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 4 with memaddress 0x15f15b60 
2016-10-24 22:10:47.118 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 2 with memaddress 0x1744d350 
2016-10-24 22:10:47.122 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 1 with memaddress 0x17351660 
2016-10-24 22:10:47.125 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 8 with memaddress 0x15f06e30 
2016-10-24 22:10:47.213 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 5 with memaddress 0x1710b1b0 

당신이 볼 수 있듯이, 세포 17 (0x17351660) 숨겨진 나는 그것의 요청을 취소합니다.

2016-10-24 22:10:46.284 Fotoloop[9834:4281410] >>>>>>HIDDING CELL 17 WITH MEMADDRESS 0x17351660 
2016-10-24 22:10:46.286 Fotoloop[9834:4281410] >>>>>>2ND CANCEL CELL 17 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 

그 직후에 셀 1 (0x17351660)이 표시되고이 셀에 대한 새 요청이 초기화됩니다.

2016-10-24 22:10:46.298 Fotoloop[9834:4281410] >>>>>>SHOWING CELL 1 WITH MEMADDRESS 0x17351660 
2016-10-24 22:10:46.298 Fotoloop[9834:4281410] >>>>>>1ST CANCEL CELL 1 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 
2016-10-24 22:10:46.301 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 1 with memaddress 0x17351660 
2016-10-24 22:10:46.303 Fotoloop[9834:4281410] >>>>>>LOADING CELL 1 WITH MEMADDRESS 0x17351660 AND REQUESTID 351 

은 그러나 잠시 후 나는이 있습니다

2016-10-24 22:10:46.551 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 17 with memaddress 0x17351660 
2016-10-24 22:10:47.122 Fotoloop[9834:4281410] >>>>>>Assigning photo to cell 1 with memaddress 0x17351660 

을 그리고 두 번째에 해당 셀에 표시된 두 이미지를 볼 수 있습니다. isRowVisible 블록의 주석 처리를 제거한 경우이 못생긴 효과는 나타나지 않지만 많은 양의 사진이있는 성능 저하로 이어질 수있는 코드 요청을 취소하는 데 문제가 있다고 생각합니다. 여기에 무엇이 누락 되었습니까?

+0

누군가 내게 같은 문제가있는 경우를 대비해서 의견을 추가하고 싶습니다. iOS 10에서 작업하는 경우, 기본적으로 iOS 10에서 cellForItemAtIndexPath가 호출되기 전에 내 method isRowVisible이 false를 매우 자주 반환합니다. 이것을 피하려면 [mycollectionview setPrefetchingEnabled : NO]를 넣어야했습니다. – Wonton

답변

0

UICollectionView에 Photos를 구현하고 있으며 사용자와 동일한 결과를 발견했습니다. 처음에는 cancelImageRequest가 작동하지 않는다고 생각했습니다. 왜냐하면 빠르게 스크롤 할 때 성능이 떨어졌고 마침내 올바른 이미지에 착륙 할 때까지 셀을 통해 2-3 개의 이미지가 깜박 거려야했기 때문입니다. 나는 또한 collectionView didEndDisplaying을 취소하더라도 PHImageCancelledKey가 결코 resultHandler 정보 사전에 존재하지 않는다는 것을 알아 차렸다.

그러나 지금 설명 할 문제를 해결했습니다. PHImageManager requestImage는 비동기식이기 때문에 백그라운드 대기열에서 실행되고 UI와 관련된 모든 작업을 수행 할 때 이상한 결과가 발생할 수 있습니다. resultHandler에서 메인 큐에있는 모든 것을 처리해야한다. 그러면 문제가 해결된다. 적어도 그것은 나를 위해했다.

800 이미지를 스크롤하는 iPhone 5s에서 테스트 중입니다.

다음은 현재 테스트중인 collectionView 코드 샘플입니다.

또한 아래에서 내 사진 가져 오기 결과를로드하고 캐시합니다. 내가 사용하는 self.imageManager는 PHCachingImageManager입니다.

방금 ​​추가하려는 것은 wasCancelled 및 isSameRequest에 대한 부울 검사가 있음을 알 수 있습니다. 취소 된 키가 존재하지 않으므로 모든 것이 메인 큐에서 처리되므로 더 이상 이미지가 깜박 거리지 않으므로 이러한 키는 무의미합니다. 나는 너를 너 자신을 위해보고 싶었던 그들을 거기두고 갔다.

// MARK: UICollectionViewDelegate 

public func numberOfSections(in collectionView: UICollectionView) -> Int 
{ 
    return 1 
} 

public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
{ 
    if let assetFetchResult = self.assetFetchResult 
    { 
     return assetFetchResult.count 
    } 

    return 0 
} 

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
{ 
    let cell: PhotoLibraryCell = self.itemsCollectionView.dequeueReusableCell(withReuseIdentifier: PhotoLibraryCell.ReuseIdentifier, for: indexPath) as! PhotoLibraryCell 

    cell.backgroundColor = .white 
    cell.drawBorder(color: .lightGray, borderWidth: 1) 
    cell.imageView.image = nil 

    if let assetFetchResult = self.assetFetchResult 
    { 
     let asset: PHAsset = assetFetchResult.object(at: indexPath.row) 
     let itemSize: CGSize = Settings.ItemSize 
     let targetSize: CGSize = CGSize(width: itemSize.width * 2, height: itemSize.height * 2) 

     if (asset.mediaType == .image) 
     { 
      cell.imageRequestID = self.imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: nil, resultHandler: { (image: UIImage?, info: [AnyHashable: Any]?) in 

       DispatchQueue.main.async { 

        var isDegraded: Bool = false 
        var wasCancelled: Bool = false 
        var isSameRequest: Bool = false 

        if let degraded = (info?[PHImageResultIsDegradedKey] as? NSNumber)?.boolValue 
        { 
         isDegraded = degraded 
        } 

        if let cancelled = (info?[PHImageCancelledKey] as? NSNumber)?.boolValue 
        { 
         wasCancelled = cancelled 
        } 

        if let id = info?[PHImageResultRequestIDKey] as? NSNumber, let cellRequestID = cell.imageRequestID 
        { 
         let requestID: Int = id.intValue 

         isSameRequest = Int(cellRequestID) == requestID 
        } 

        if (!isDegraded && !wasCancelled && isSameRequest) 
        { 
         cell.imageView.image = image 
        } 
       } 
      })     
     } 
     else if (asset.mediaType == .video) 
     { 

     } 
    } 

    return cell 
} 

public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) 
{ 
    if let photoLibraryCell = cell as? PhotoLibraryCell 
    { 
     if let imageRequestID = photoLibraryCell.imageRequestID 
     { 
      self.imageManager.cancelImageRequest(imageRequestID) 
     } 
    } 
} 

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
{ 
    return Settings.ItemSize 
} 

// MARK: Assets 

public func reloadAssets() 
{ 
    let photoResult: PHFetchResult<PHAsset> = PHAsset.fetchAssets(with: .image, options: nil) 

    self.assetFetchResult = photoResult 

    self.itemsCollectionView.reloadData() 

    //enumerate assets and start caching them 
    let backgroundQueue: DispatchQueue = DispatchQueue(label: "enumerate-phassets-background-queue", qos: .background, target: nil) 
    backgroundQueue.async { 

     var assets: [PHAsset] = Array() 
     let itemSize: CGSize = Settings.ItemSize 
     let targetSize: CGSize = CGSize(width: itemSize.width * 2, height: itemSize.height * 2) 

     photoResult.enumerateObjects({ (asset: PHAsset, index: Int, stopEnumeration: UnsafeMutablePointer<ObjCBool>) -> Void in 
      assets.append(asset) 

      let reachedEnd: Bool = index == photoResult.count - 1 
      if (reachedEnd) 
      { 
       self.imageManager.startCachingImages(for: assets, targetSize: targetSize, contentMode: .aspectFill, options: nil) 
      } 
     }) 
    } 
} 
관련 문제