Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS PHImageManager cancelImageRequest不工作?_Ios_Objective C_Uicollectionview - Fatal编程技术网

iOS PHImageManager cancelImageRequest不工作?

iOS PHImageManager cancelImageRequest不工作?,ios,objective-c,uicollectionview,Ios,Objective C,Uicollectionview,我正在使用照片框架填充UICollectionView。这应该是一个简单的模式,但我在取消隐藏单元格的请求时遇到了问题 这是我的代码,摘自几个示例: #pragma mark - UICollectionView DataSource - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (NSInteger)collectionView:(UIC

我正在使用照片框架填充UICollectionView。这应该是一个简单的模式,但我在取消隐藏单元格的请求时遇到了问题

这是我的代码,摘自几个示例:

#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;
}
如果我在集合视图中快速向下和向上滚动,每个单元格都会刷新几次,在1到2秒内显示2个甚至3个图像。 当单元格不再可见或单元格再次可见时,我尝试取消同一单元格中的上一个请求,但查看结果和日志,似乎没有取消任何请求

这些是我向下滚动和向上滚动到列表顶部后的日志

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块的注释,我看不到这种丑陋的效果,但我一直认为用我的代码取消请求存在问题,这可能会导致大量照片的性能不佳。
我在这里遗漏了什么?

我正在将照片实现到UICollectionView中,并发现了与您相同的结果。起初,我认为cancelImageRequest不起作用,因为当快速滚动时,性能会受到影响,我会看到2-3个图像在单元格中闪烁,直到最终到达正确的图像。我还注意到,PHIMAGECANCELEDKEY将永远不会存在于resultHandler信息字典中,即使我正在collectionView DiEndDisplaying上取消

不过,我确实解决了我的问题,我现在将对此进行解释。因为PHImageManager requestImage是异步的,所以它很可能在后台队列上运行,这在执行任何与UI相关的操作时都会导致奇怪的结果。在resultHandler中,确保处理主队列上的所有内容,它应该能够解决您看到的问题。至少对我来说是这样

我正在iPhone 5s上测试,它可以滚动800张图片

下面是我当前测试的collectionView代码示例

我还在下面提供了加载照片获取结果并缓存它们的位置。我使用的self.imageManager是PHCachingImageManager

只想补充一点,您会注意到我对wascelected和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)
            }
        })
    }
}
//标记:UICollectionViewDelegate
public func numberOfSections(在collectionView:UICollectionView中)->Int
{
返回1
}
公共函数集合视图(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int
{
如果让assetFetchResult=self.assetFetchResult
{
返回assetFetchResult.count
}
返回0
}
公共函数collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell
{
将cell:PhotoLibraryCell=self.itemsCollectionView.dequeueReusableCell(带ReuseIdentifier:PhotoLibraryCell.ReuseIdentifier,for:indexPath)设为!PhotoLibraryCell
cell.backgroundColor=.white
单元格.绘图边框(颜色:。浅灰色,边框宽度:1)
cell.imageView.image=nil
如果让assetFetchResult=self.assetFetchResult
{
让asset:PHAsset=assetFetchResult.object(位于:indexPath.row)
让itemSize:CGSize=Settings.itemSize
让targetSize:CGSize=CGSize(宽度:itemSize.width*2,高度:itemSize.height*2)
如果(asset.mediaType==.image)
{
cell.imageRequestID=self.imageManager.requestImage(for:asset,targetSize:targetSize,contentMode:.aspectFill,options:nil,resultHandler:{(image:UIImage?,info:[AnyHashable:Any]?)中的
DispatchQueue.main.async{
var已降级:布尔=假
var已取消:Bool=false
变量isSameRequest:Bool=false
如果让降级=(信息?[PHImageResultIsDegradedKey]作为?NSNumber)?.boolValue
{
isDegraded=降级
}
如果让已取消=(信息?[PHImageCancelledKey]作为?NSNumber)?.boolValue
{
取消
}
如果让id=info?[PhimageResultRequestKey]作为?NSNumber,则让cellRequestID=cell.imageRequestID
{
让requestID:Int=id.intValue
isSameRequest=Int(cellRequestID)=requestID
}
如果(!isDegraded&&!已取消&&isSameRequest)
{
cell.imageView.image=图像
}
}
})                
}
else if(asset.mediaType==.video)
{
}
}
返回单元
}
public func collectionView(collectionView:UICollectionView,DiEndDisplaying单元格:UICollectionViewCell,forItemAt indexPath:indexPath)
{
如果let photoLibraryCell=单元as?photoLibraryCell
{
如果让imageRequestID=photoLibraryCell.imageRequestID
{
self.imageManager.cancelImageRequest(imageRequestID)
}
}
}
public func collectionView(collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:indexPath)->CGSize
{
返回设置.ItemSize
}
//马克:资产
公共函数重新加载资产()
{
让photoResult:PHFetchResult=PHAsset.fetchAssets(带:.image,选项:nil)
self.assetFetchResult=照片结果
self.itemsCollectionView.reloadData()
//枚举资产并开始缓存它们
let backgroundQueue:DispatchQueue=Di