我正在尝试使用PHAssetResourceManager
从资产中获取数据。
我找不到任何关于此的例子。
我曾经使用PHImageManager
但我的应用程序要到明年才会发布
所以到那时我猜大多数人很可能会采用最新的
iOS版本无论如何。
尝试记录指定资产的资源时,以下代码返回“0”。
如何使用PHAssetResourceManager
?
我的代码:
PHFetchOptions *fetchOptions;
fetchOptions.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES], ];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithOptions:fetchOptions];
NSLog(@"fetchResult.count = %lu", fetchResult.count);
PHAsset *asset = [fetchResult objectAtIndex: assetIndex];
NSArray *resourceArray = [PHAssetResource assetResourcesForAsset: asset];
NSLog(@"resourceArray.count = %lu", resourceArray.count); //<<< returns 0?
PHAssetResource *ar = [resourceArray objectAtIndex: 0];
PHAssetResourceRequestOptions *arro = [[PHAssetResourceRequestOptions alloc] init];
PHAssetResourceManager *arm = [PHAssetResourceManager defaultManager];
[arm requestDataForAssetResource:ar options:arro
dataReceivedHandler:^(NSData *assetData){
NSLog(@"extractData dataReceivedHandler: %lu", assetData.length);
}
completionHandler:^(NSError *error){
NSLog(@"extractData Error: %@", error);
}
];
});
答案 0 :(得分:1)
我从模拟器中的视图控制器viewDidLoad方法调用以下方法,一切正常。
- (void)readAsset:(NSInteger)assetIndex {
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES] ];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithOptions:fetchOptions];
if (assetIndex < fetchResult.count) {
PHAsset *asset = fetchResult[assetIndex];
NSArray *resourceArray = [PHAssetResource assetResourcesForAsset: asset];
PHAssetResource *assetResource = resourceArray[0];
PHAssetResourceManager *arm = [PHAssetResourceManager defaultManager];
[arm requestDataForAssetResource:assetResource options:nil dataReceivedHandler:^(NSData * _Nonnull data) {
NSLog(@"data.length = %lu", (unsigned long)data.length);
} completionHandler:^(NSError * _Nullable error) {
NSLog(@"error = %@", error);
}];
}
else {
NSLog(@"no such asset.");
}
}
输出结果为:
fetchResult.count = 5
data.length = 1048576
data.length = 1048576
data.length = 507598
data.length = 0
error = (null)
你能弄清楚你的代码和我的代码有什么不同吗?我唯一看到的是你在使用之前不创建PHFetchOptions对象。这是未定义的行为。