iOS 通过照片assets-library地址查找对应的照片

2019-07-09  本文已影响0人  王家薪

保存相册后 我们会得到 assets-library://asset/asset.JPG?id=9581C151-4582-4ABD-A581-1F34E037E1A0&ext=JPG 酱紫的图片地址, 问题是如何通过这个地址拿到对应的图片呢?

方法1 网上大部分的解决方案, 但是ALAssetsLibrary类已经被 apple 无情的抛弃了
ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:imagePath resultBlock:^(ALAsset *asset){
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    CGImageRef iref = [rep fullScreenImage];
}

方法2 通过 ALAssetsLibrary 弃用提示找到的方法, 但是这个方法也被弃用了T_T
+ (PHFetchResult<PHAsset *> *)fetchAssetsWithALAssetURLs:(NSArray<NSURL *> *)assetURLs options:(nullable PHFetchOptions *)options 
API_DEPRECATED("Will be removed in a future release", ios(8.0, 11.0), tvos(8.0, 11.0));

解决方案 使用 PHAsset fetchAssetsWithLocalIdentifiers: options:]
    // 这里是原本的图片url
    NSString * path = @"assets-library://asset/asset.JPG?id=9581C151-4582-4ABD-A581-1F34E037E1A0&ext=JPG";
    // 取出要使用的 LocalIdentifiers
    NSString * usePath = @"9581C151-4582-4ABD-A581-1F34E037E1A0";
    PHFetchResult * re = [PHAsset fetchAssetsWithLocalIdentifiers:@[usePath] options:nil];
    [re enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@", obj.localIdentifier);
        [[PHCachingImageManager defaultManager] requestImageDataForAsset:obj options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            
            UIImage * img = [UIImage imageWithData:imageData];
            
            self.imageView.image = img;
            
        }];
    }];
上一篇下一篇

猜你喜欢

热点阅读