Traps for PHAsset. How to get filename from PHAsset?

Kuang Lin
1 min readJun 4, 2019

--

PHAsset it the object that iOS provided for developers to get the data of media files.

We can get images, videos from the API:

PHAsset.fetchAssets(in assetCollection: PHAssetCollection, options: PHFetchOptions?) -> PHFetchResult<PHAsset>

The PHFetchResult can be unwrapped by :

let phAssets = phFetchResult.objects(at: IndexSet(0 ..< phFetchResult.count))

or

PHFetchResult.enumerateObjects(_ block: @escaping (ObjectType, Int, UnsafeMutablePointer<ObjCBool>) -> Void)

The block will provide every asset in the result through the first argument.

Now here’s the point.

How do we get filename from PHAsset?

The document tells you to get the asset filename through the api(after iOS9):

let resources = PHAssetResource.assetResources(for: phAsset)let fileName = resources.first?.originalFilename

But this will takes you 7~15 ms. which will be a big deal if you want to query the filenames of all the photos in album.

So there’s a tricky property that is not written in Document.

phAsset.value(forKey: "filename")

This will do the trick.

But since this is not official in document, we don’t know when the api will stop working.

So make sure you check the filenames is still working everytime when the OS is upgraded.

--

--