Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHAsset (or ALAsset) cross-device identifier

I am actually creating an iOS app, and want to store some details about Photo Library pictures in an SQLite database. I also would like to be able to share this data across the different devices the user has (imagine someone wanted to reorganize pictures on his iPhone, and wants to retrieve the same order in his iPad).

I have searched across the Apple documentation, but did not find any PHAsset identifier that is shared across devices. I also tried to check if the PHImageFileURLKey, hashValue, or localIdentifier of the PHAsset where shared, but none of them are.

Has someone already done something like this?

like image 636
Lucio Avatar asked Feb 24 '15 07:02

Lucio


2 Answers

There is none at the moment. PHAsset had a shared identifier in the first iOS 8 Betas, but it was removed later on.

like image 122
holtmann Avatar answered Nov 16 '22 22:11

holtmann


Since iOS 15 there is an identifier that is available across all devices: https://developer.apple.com/documentation/photokit/phcloudidentifier

The API is pretty simple. The idea is that you store and sync cloud identifiers and then use them to retrieve local identifiers, which you then can use with existing API's like you are used to. You can request the cloud identifiers in batches, like so:

let localIdentifiers = <your-list-of-local-identifiers>
let mappings: [String: Result<PHCloudIdentifier, Error>] = 
  PHPhotoLibrary.shared().cloudIdentifierMappings(forLocalIdentifiers: localIdentifiers)

You can store such identifiers by using the stringValue property.

Vice versa (say you have a list of cloudIdentifiers with the string values of the identifiers):

let localIdentifiers: [PHCloudIdentifier: Result<String, Error>]
   = PHPhotoLibrary
        .shared()
        .localIdentifierMappings(
          for: cloudIdentifiers.map(PHCloudIdentifier.init(stringValue:)))

What errors can happen?

  • No identifier was found: Either you passed in an invalid identifier or the asset has been deleted
  • Multiple local identifiers for a cloud identifier where found (According to WWDC this happens if "Cloud state isn't in sync or the library relies on image content to find a match") More info about the error handling here

Additional insights that i derived through experimentation:

  • You seem to be able to get cloud identifiers without internet, with iCloud disabled for your app even without being signed into an iCloud account at all.
  • Even though the doc states it's an expensive operation, the overhead for loading some hundreds of identifiers at once is not noticeable for me
like image 2
Falco Winkler Avatar answered Nov 16 '22 23:11

Falco Winkler