iosswiftmultithreadingphotosframework

Can I fetch PHAssets in a background thread?


I want to do some work on a user's photo library. Since the library can be huge, I want to do it in the background. I'm wondering whether it is safe to perform asset fetches (like PHAsset.fetchAssets) and work on them in the background?

I only need the asset metadata for now.

Would something like this be safe:

class ViewController: UIViewController {

    var cachedResult = [Any]()

    func doBackgroundCalculationsOnPhotos(completionHandler: ([Any]) -> ()) {
        DispatchQueue.global(qos: .userInitiated).async {
            let photos = PHAsset.fetchAssets(with: .image, options: nil)
            var result = [Any]()

            photos.enumerateObjects({ asset, _, _ in  
                result.append(calculateSomething(asset))
            })

            DispatchQueue.main.async {
                self.cachedResult = result
                completionHandler(result)
            }
        }
    }
}

Are there any references to documentation where I could learn about Photos Framework and background access?


Solution

  • Yes, it can take some time to fetch so it might be a good idea to do this in the background as the fetchAssets(with:options:) method is synchronous.