PHAsset, how to retrieve the specific PHAsset object after app restarts (ios8 Photos)

Bruce Tsai picture Bruce Tsai · Feb 23, 2016 · Viewed 9.6k times · Source

I used to use ALAssetLibrary. And it has assetForURL function, so that I can save the URL in to NSUserDefaults and to retrieve ALasset by URL after app restarts.

However, when I change to PHAsset, I can't find this kind of function. What I found is fetchAssetsWithALAssetURLs, but it will be deprecated for ALasset, so I don't tend to use this function. (save ALAsset url , and retrieve PHAsset from fetchAssetsWithALAssetURLs)

I think it's the only way to save the whole PHAsset object into NSUserDefaults with key "localIdentifier", so I can reload it after app restarts. To retrieve phasset object is by key localIdentifier.

Is it a good way to achieve my goal? Other ways ?

Answer

Grimxn picture Grimxn · Feb 23, 2016

The key is the property .localIdentifier. It's "obscure" as it is actually a property of the super-class PHObject. Here's what the docs say:

A unique string that persistently identifies the object. (read-only)

Declaration

SWIFT

var localIdentifier: String { get }

Discussion

Use this string to find the object by using the fetchAssetsWithLocalIdentifiers:options:, fetchAssetCollectionsWithLocalIdentifiers:options:, or fetchCollectionListsWithLocalIdentifiers:options: method.