Can I fetch PHAssets in a background thread?
Asked Answered
M

1

10

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?

Medusa answered 15/6, 2017 at 9:1 Comment(1)
I have the same question.Application
S
2

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.

Steel answered 3/12, 2019 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.