Search code examples
iosswiftphotokit

Synchronous method for accessing URL info for PHAsset objects


Are there any approaches for getting the URL of a PHAsset that does not involve asynchronous requests/processes?

I realize that blocking the main thread when making requests like this is a no-no, but if you have a small number of assets to query, is it possible to get them any other way?

So far, the only ways I've found to get asset URLs seem to be things like the following:

somePHAssetObject.requestContentEditingInput(with: nil, completionHandler: {
                input, info in
                guard let input = input
                    else { fatalError("can't get info: \(info)") }

                let assetURL = input.audiovisualAsset as! AVURLAsset

            })

Or

    PHCachingImageManager().requestAVAsset(forVideo: SomePHAssetObject, options: nil, resultHandler: {
(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable: Any]?) in

                    let vidURL = asset as! AVURLAsset

                })

Are there any ways to do something like this without an async approach? I'm just not seeing a URL property anywhere on a PHAsset, but could be missing something really obvious.


Solution

  • I don't believe that there is an API like that, but you can force the thread to wait for the handler using semaphore, e.g., for the second example you have presented:

    let semaphore = DispatchSemaphore(value: 0)
    PHCachingImageManager().requestAVAsset(forVideo: SomePHAssetObject, options: nil, resultHandler: { (asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable: Any]?) in
    
        let vidURL = asset as! AVURLAsset
    
        semaphore.signal()
    })
    
    _ = semaphore.wait(timeout: DispatchTime.distantFuture)
    

    Although I really don't understand why you would want to do it synchrously.