我想知道有没有办法使用PHAsset获取原始文件名?
//首先获取 PHAsset
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
//
if (status == PHAuthorizationStatusAuthorized){
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
//获取相册里面数据
PHFetchResult<PHAsset *> *phAsset = [PHAsset fetchAssetsWithOptions:options];
[phAsset enumerateObjectsUsingBlock:^(PHAsset * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
}];
}
}];
//方法 1
//这种方法是通过获取图片的URL路径,然后再获取图片名称。经过多次测试,图片URL路径有时候可以获取到,有时候获取不到,所以会导致图片名称有时候获取不到,所以这种方法并不靠谱。
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:requestOption resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
entity.fileUrl = [info objectForKey:@"PHImageFileURLKey"];
entity.filename = [[NSFileManager defaultManager] displayNameAtPath:[ entity.fileUrl path]];
}];
However, It doesn't return original name but the name in the format "img_123" 然而不是写入相册的name,而是相册数据自己维护的一个新name,Img_2213.xx I've just checked official apple docs . there has been introduced a new class PHAssetResource and the property originalFilename which is available in the iOS 9+. On iOS 8 your solution is the right (and only approach) to get a filename at all.
//方法 2 解决 best Answers
On iOS 9 this works:
NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
NSString *orgFilename = ((PHAssetResource*)resources[0]).originalFilename;
//方法 3 这种方法拿到的还是 Img_2213.xxx
NSString *filename = [asset valueForKey:@"filename"];
NSLog(@"filename:%@",filename);