ios 检查给定的PHAsset是否为iCloud资产?

ztigrdn8  于 2023-03-14  发布在  iOS
关注(0)|答案(7)|浏览(167)

我正在尝试获取PhAsset对象。我想隔离iCloud资源。这是我的代码,

PHFetchResult *cloudAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];

[cloudAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop){
    if(collection != nil){

        PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
        [result enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop)
         {
            // check asset is iCloud asset 

         }];
    }

}];

请告诉我如何找到PHAsset是iCloud资产?

flvtvl50

flvtvl501#

这有点像黑客,我不得不挖掘资源数组并调试以找到我需要的信息。但它工作。虽然这是一个未记录的代码,我不确定苹果是否会因此拒绝应用程序。给予它一个尝试,看看会发生什么!

// asset is a PHAsset object for which you want to get the information    
NSArray *resourceArray = [PHAssetResource assetResourcesForAsset:asset];
BOOL bIsLocallayAvailable = [[resourceArray.firstObject valueForKey:@"locallyAvailable"] boolValue]; // If this returns NO, then the asset is in iCloud and not saved locally yet

您还可以从资产资源中获得一些其他有用的信息,如原始文件名、文件大小、文件URL等。

nnsrf1az

nnsrf1az2#

实际上有两种情况:1.照片由本设备拍摄,并上传到iCloud,然后您可以使用progressHandler检查是否需要iCloud下载。

__block BOOL isPhotoInICloud = NO;
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.networkAccessAllowed = YES;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info){

        isPhotoInICloud = YES;

});

[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

        if (isPhotoInICloud) {
            // Photo is in iCloud.
        }
});

1.照片在iCloud中,但从其他设备上传。并且您没有将其保存到本地照片库。因此progressHandler块永远不会被调用。我不知道为什么,但这是真的,我认为这是PhotoKit框架的一个bug。对于这种情况,如果您使用PHImageResultIsInCloudKey,这也很困难,因为你可以在requestImageForAsset的resultHandler块中知道PHImageResultIsInCloudKey的值,但那是照片请求启动后的时间。
所以,至少,在我看来,没有办法检查照片是否存储在iCloud。也许有其他更好的方法,请让我知道。非常感谢!

db2dz4w8

db2dz4w83#

当你请求一张图片时,你会在信息字典中得到一个关键字,它会告诉你该资产是否存在于iCloud中。

[cloudAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop)
{
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions];
    [result enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop)
    {  
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.resizeMode = PHImageRequestOptionsResizeModeFast;
        options.synchronous = YES;
        __block BOOL isICloudAsset = NO;
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) 
        {
            if ([info objectForKey: PHImageResultIsInCloudKey].boolValue) 
            {
                isICloudAsset = YES;
            }
        }]; 
    }];
}];
gkn4icbw

gkn4icbw4#

这是Swift 3的版本

func checkVideoType(){
    if selectedAsset != nil {
        guard (selectedAsset.mediaType == .video) else {
            print("Not a valid video media type")
            return
        }
        requestID = checkIsiCloud(assetVideo:selectedAsset, cachingImageManager: catchManager)
    }
}

 func checkIsiCloud(assetVideo:PHAsset,cachingImageManager:PHCachingImageManager) -> PHImageRequestID{

        let opt=PHVideoRequestOptions()
        opt.deliveryMode = .mediumQualityFormat
        opt.isNetworkAccessAllowed=true //iCloud video can play
        return cachingImageManager.requestAVAsset(forVideo:assetVideo, options: opt) { (asset, audioMix, info) in

            DispatchQueue.main.async {
                if (info!["PHImageFileSandboxExtensionTokenKey"] != nil) {
                    self.iCloudStatus=false
                    self.playVideo(videoAsset:asset!)
                }else if((info![PHImageResultIsInCloudKey]) != nil) {
                    self.iCloudStatus=true

                }else{
                   self.iCloudStatus=false
                   self.playVideo(videoAsset:asset!)
                }
            }
    }

}
8aqjt8rx

8aqjt8rx5#

以下是您可以实现的获取“照片”应用的“视频”文件夹中所有视频的方法,该方法使用PHFetchRequest predicate 仅过滤存储在iPhone本身上的视频,而不是存储在iCloud中的视频:

// Collect all videos in the Videos folder of the Photos app
- (PHFetchResult *)assetsFetchResults {
    __block PHFetchResult *i = self->_assetsFetchResults;
    if (!i) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            PHFetchOptions *fetchOptions = [PHFetchOptions new];
            fetchOptions.predicate = [NSPredicate predicateWithFormat:@"(sourceType & %d) != 0", PHAssetSourceTypeUserLibrary];
            PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:fetchOptions];
            PHAssetCollection *collection = smartAlbums.firstObject;
            if (![collection isKindOfClass:[PHAssetCollection class]]) collection = nil;
            PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
            allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            i = [PHAsset fetchAssetsInAssetCollection:collection options:allPhotosOptions];
            self->_assetsFetchResults = i;
        });
    }

    return i;
}

Apple关于PHFetchResult的文档指出,只有属性的子集可以与 predicate 一起使用;因此,如果上面的代码不适合您,请删除PHFetchOptions predicate ,并将PHFetchRequest中的相应引用替换为nil:

// Collect all videos in the Videos folder of the Photos app
- (PHFetchResult *)assetsFetchResults {
    __block PHFetchResult *i = self->_assetsFetchResults;
    if (!i) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
            PHAssetCollection *collection = smartAlbums.firstObject;
            if (![collection isKindOfClass:[PHAssetCollection class]]) collection = nil;
            PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
            allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            i = [PHAsset fetchAssetsInAssetCollection:collection options:allPhotosOptions];
            self->_assetsFetchResults = i;
        });
    }

    return i;
}

然后,添加以下行:

// Filter videos that are stored in iCloud
- (NSArray *)phAssets {
    NSMutableArray *assets = [NSMutableArray arrayWithCapacity:self.assetsFetchResults.count];
    [[self assetsFetchResults] enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
        if (asset.sourceType == PHAssetSourceTypeUserLibrary)
                 [assets addObject:asset];
     }];

    return [NSArray arrayWithArray:(NSArray *)assets];
}
gywdnpxw

gywdnpxw6#

这段代码应该可以工作。2如果经常调用这段代码,请确保通过PHImageRequestID取消无用的请求。

- (PHImageRequestID)checkIsCloud:(PHAsset *)asset cachingImageManager:(PHCachingImageManager *)cachingImageManager {
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        PHVideoRequestOptions *options = [PHVideoRequestOptions new];
        options.deliveryMode = PHVideoRequestOptionsDeliveryModeMediumQualityFormat;
        return [cachingImageManager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
            if (asset != self.asset) return;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (info[@"PHImageFileSandboxExtensionTokenKey"]) {
                    self.iCloudStatus = KICloudStatusNone;
                } else if ([info[PHImageResultIsInCloudKey] boolValue]) {
                    self.iCloudStatus = KICloudStatusNormal;
                } else {
                    self.iCloudStatus = KICloudStatusNone;
                }
            });
        }];
    } else {
        return [cachingImageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            if (asset != self.asset) return;
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([info[PHImageResultIsInCloudKey] boolValue]) {
                    self.iCloudStatus = KICloudStatusNormal;
                } else {
                    self.iCloudStatus = KICloudStatusNone;
                }
            });
        }];
    }
}
hmmo2u0o

hmmo2u0o7#

这是Swift 5版本

extension PHAsset {
   var isLocallyAvailable: Bool? {
      let resourceArray = PHAssetResource.assetResources(for: self)
      return resourceArray.first?.value(forKey: "locallyAvailable") as? Bool
   }
}

相关问题