Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
tombardey Avatar asked Jun 15 '17 09:06

tombardey


People also ask

How do I get a PHAsset UIImage?

Use this method if you only need UIImage from PHAsset . extension PHAsset { func image(targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?) -> UIImage { var thumbnail = UIImage() let imageManager = PHCachingImageManager() imageManager.

What is PHAsset in Swift?

A representation of an image, video, or Live Photo in the Photos library.


1 Answers

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.

like image 50
Ludovic Landry Avatar answered Oct 01 '22 13:10

Ludovic Landry