简体   繁体   中英

Get File Extension from a PHAsset in iOS 8?

Is there any way to distinguish a PHAsset's file extension? My app needs to know if the photo is a .GIF or not. I'm not seeing any way to do this.

A better approach would be to use uniformTypeIdentifier. Files can be named anything and may or may not contain a file extension.

[asset valueForKey:@"uniformTypeIdentifier"];

Using valueForKey: you can get the PHAsset file name from that you extract file extension using "pathExtension" For Example: PHAsset *selectedAsset = ...

NSString *fileName =[selectedAsset valueForKey:@"filename"];
NSString * fileExtension = [fileName pathExtension];

File names are an implementation detail, and may or may not tell you what the content of a file really is.

When you call requestImageDataForAsset , the dataUTI parameter that Photos passes to your completion handler tells you the Uniform Type Identifier for the image data.

PHAssetResource.uniformTypeIdentifier seems to do the job. PHAsset s can be fetched by using the class function PHAssetResource. assetResources(for:) PHAssetResource. assetResources(for:) .

An image does NOT mean only there will be only one item in the list, so check out the documentation.

在 Swift 中,使用:

URL(fileURLWithPath: (asset.value(forKey: "filename") as! String)).pathExtension

Swift 5 Elegant Solution

extension PHAsset {
    func getFileName() -> String? {
        return self.value(forKey: "filename") as? String
    }

    func getExtension() -> String? {
        guard let fileName = self.getFileName() else {
            return nil
        }
        return URL(fileURLWithPath: fileName).pathExtension
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM