Get ALAsset or PHAsset from file url

Selecting images in Photos.app to go to the extension of the action seems to give paths to the images on the disk (for example: file:///var/mobile/Media/DCIM/109APPLE/IMG_9417.JPG ). Is there a way to get the appropriate ALAsset or PHAsset?

The url looks like it matches the PHImageFileURLKey entry that you get from calling PHImageManager.requestImageDataForAsset . I would really like him to iterate over all the PHAssets to find it.

+6
source share
3 answers

I did what I did not want to do, and threw this dumb search approach. It works, although it is terrible, slow and gives me memory problems when the photo library is large.

As a noob for both Cocoa and Swift, I would appreciate clarification tips. Thanks!

 func PHAssetForFileURL(url: NSURL) -> PHAsset? { var imageRequestOptions = PHImageRequestOptions() imageRequestOptions.version = .Current imageRequestOptions.deliveryMode = .FastFormat imageRequestOptions.resizeMode = .Fast imageRequestOptions.synchronous = true let fetchResult = PHAsset.fetchAssetsWithOptions(nil) for var index = 0; index < fetchResult.count; index++ { if let asset = fetchResult[index] as? PHAsset { var found = false PHImageManager.defaultManager().requestImageDataForAsset(asset, options: imageRequestOptions) { (_, _, _, info) in if let urlkey = info["PHImageFileURLKey"] as? NSURL { if urlkey.absoluteString! == url.absoluteString! { found = true } } } if (found) { return asset } } } return nil } 
+4
source

So, this is a comment on ("refinement tips") for your autoresponse. SO comments don't shorten it for code samples, so we go.

  • You can replace the for-index loop with a simpler one for each loop. For instance. sort of:

     for asset in PHAsset.fetchAssetsWithOptions(nil) 
  • As of the last time I checked, the key in info["PHImageFileURLKey"] documented. Be careful. I do not think this will reject you, but the behavior may change at any time.

+1
source

Question: Why do you want to do this? Do you want to call / use any methods from PhotoKit? I would prefer to work directly with the file that Photos-App transfers.

0
source

Source: https://habr.com/ru/post/982857/