Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

ios8 - Retrieve ALAsset or PHAsset from file URL

Selecting images in Photos.app to pass to an action extension seems to yield paths to images on disk (e.g.: file:///var/mobile/Media/DCIM/109APPLE/IMG_9417.JPG). Is there a way to get the corresponding ALAsset or PHAsset?

The URL looks like it corresponds to the PHImageFileURLKey entry you get from calling PHImageManager.requestImageDataForAsset. I'd hate to have to iterate through all PHAssets to find it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I did what I didn't want to do and threw this dumb search approach together. It works, although it's horrible, slow and gives me memory issues when the photo library is large.

As a noob to both Cocoa and Swift I'd appreciate refinement 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...