iOS8 Photos Framework:如何获取PHAsset的名称(或文件名)? [英] iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?

查看:1193
本文介绍了iOS8 Photos Framework:如何获取PHAsset的名称(或文件名)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 PHAssets 获取图像名称。但我找不到文件名元数据或任何获取图像名称的方法。是否有不同的方法来获取文件名?

Im trying to get the image name using PHAssets. But I couldn't find metadata for filename or any method to get the image name. Is there a different way to get the file name?

推荐答案

如果要获取图像名称(例如最后一个名称)照片在照片中),如IMG_XXX.JPG,你可以试试这个:

If you want to get the image name (for example name of last photo in Photos) like IMG_XXX.JPG, you can try this:

PHAsset *asset = nil;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
    // get last photo from Photos
    asset = [fetchResult lastObject];
}

if (asset) {
    // get photo info from this asset
    PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
    imageRequestOptions.synchronous = YES;
    [[PHImageManager defaultManager]
             requestImageDataForAsset:asset
                            options:imageRequestOptions
                      resultHandler:^(NSData *imageData, NSString *dataUTI,
                                      UIImageOrientation orientation, 
                                      NSDictionary *info) 
     {
          NSLog(@"info = %@", info);
          if ([info objectForKey:@"PHImageFileURLKey"]) {
               // path looks like this - 
               // file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
               NSURL *path = [info objectForKey:@"PHImageFileURLKey"];
     }                                            
    }];
}

希望有所帮助。

在Swift中代码看起来像这样

In Swift the code will look like this

PHImageManager.defaultManager().requestImageDataForAsset(asset, options: PHImageRequestOptions(), resultHandler:
{
    (imagedata, dataUTI, orientation, info) in
    if info!.keys.contains(NSString(string: "PHImageFileURLKey"))
    {
        let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL
    }
})

Swift 4

PHImageManager.default().requestImageData(for: asset, options: PHImageRequestOptions(), resultHandler: 
{ (imagedata, dataUTI, orientation, info) in
            if let info = info {
                if info.keys.contains(NSString(string: "PHImageFileURLKey")) {
                    if let path = info[NSString(string: "PHImageFileURLKey")] as? NSURL {
                        print(path)
                    }
                }
            }
})

这篇关于iOS8 Photos Framework:如何获取PHAsset的名称(或文件名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆