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

ぐ巨炮叔叔 提交于 2019-11-26 11:06:21

问题


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?


回答1:


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

Hope it helps.

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:

    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)
                            }
                        }
                    }
            })
        }
    }



回答2:


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
    }
}



回答3:


One more option is:

[asset valueForKey:@"filename"]

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




回答4:


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

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



回答5:


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

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
        }
    })
}



回答6:


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

Use this string to find the object by using the:

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

More information is available here




回答7:


SWIFT4: first 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
                }
            })
        }


来源:https://stackoverflow.com/questions/27854937/ios8-photos-framework-how-to-get-the-nameor-filename-of-a-phasset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!