ios iOS8 照片框架:如何获取 PHAsset 的名称(或文件名)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27854937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:17:04  来源:igfitidea点击:

iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?

iosphasset

提问by Priyanka

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?

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

采纳答案by Eridana

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

如果你想获得像 IMG_XXX.JPG 这样的图像名称(例如照片中最后一张照片的名称),你可以试试这个:

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"];
     }                                            
    }];
}

Hope it helps.

希望能帮助到你。

In Swift the code will look like this

在 Swift 中,代码将如下所示

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:

斯威夫特 4

    let fetchResult = PHAsset.fetchAssets(with: .image, options: nil)
    if fetchResult.count > 0 {
        if let asset = fetchResult.firstObject {
            let date = asset.creationDate ?? Date()
            print("Creation date: \(date)")
            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)
                            }
                        }
                    }
            })
        }
    }

回答by skim

I know the question has already been answered, but I figured I would provide another option:

我知道这个问题已经得到了回答,但我想我会提供另一个选择:

extension PHAsset {

    var originalFilename: String? {

        var fname:String?

        if #available(iOS 9.0, *) {
            let resources = PHAssetResource.assetResources(for: self)
            if let resource = resources.first {
                fname = resource.originalFilename
            }
        }

        if fname == nil {
            // this is an undocumented workaround that works as of iOS 9.1
            fname = self.value(forKey: "filename") as? String
        }

        return fname
    }
}

回答by Leo Natan

One more option is:

另一种选择是:

[asset valueForKey:@"filename"]

The "legality" of this is up to you to decide.

这样做的“合法性”由您来决定。

回答by d4Rk

Easiest solution for iOS 9+ in Swift 4 (based on skims answer):

Swift 4 中适用于 iOS 9+ 的最简单解决方案(基于skims 答案):

extension PHAsset {
    var originalFilename: String? {
        return PHAssetResource.assetResources(for: self).first?.originalFilename
    }
}

回答by Bart?omiej Semańczyk

Simplest answer with Swift when you have reference url to an asset:

当您拥有资产的参考网址时,Swift 的最简单答案:

if let asset = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil).firstObject as? PHAsset {

    PHImageManager.defaultManager().requestImageDataForAsset(asset, options: nil, resultHandler: { _, _, _, info in

        if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {      
            //do sth with file name
        }
    })
}

回答by Ahmad Labeeb

SWIFT4:first import Photos

SWIFT4:第一个import Photos

if let asset = PHAsset.fetchAssets(withALAssetURLs: [info[UIImagePickerControllerReferenceURL] as! URL],
                                           options: nil).firstObject {


            PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { _, _, _, info in

                if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
                    print("///////" + fileName + "////////")
                    //do sth with file name
                }
            })
        }

回答by Avi Levin

What you really looking for is the localIdentifierwhich is a unique string that persistently identifies the object.

您真正要寻找的是localIdentifier,它是一个唯一的字符串,可以持久地标识对象。

Use this string to find the object by using the:

使用此字符串通过以下方式查找对象:

fetchAssetsWithLocalIdentifiers:options:, fetchAssetCollectionsWithLocalIdentifiers:options:, or fetchCollectionListsWithLocalIdentifiers:options: method.

fetchAssetsWithLocalIdentifiers:options:, fetchAssetCollectionsWithLocalIdentifiers:options:, or fetchCollectionListsWithLocalIdentifiers:options: method.

More information is available here

在此处获得更多信息