iOS 14: PHPickerViewController is there any way to load all assets at the same time PHPickerResult

6.1k views Asked by At

Currently, I am trying to dive into PHPickerViewController for select multiple image at same time from Photos. so I want to array of image that selected by user, i tried it too many way but no luck. This is my code please tell me there is an best practice for to do it?

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true, completion: nil)
        var images: [UIImage?] = []
        var totalConversionsCompleted = 0
        for (index,result) in results.enumerated() {
            result.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { (object, error) in
                let image = object as? UIImage
                images.append(image)
                totalConversionsCompleted += 1
                if totalConversionsCompleted == index {
                    print("completion happen \(images)")
                }
            })
        }
    }
3

There are 3 answers

1
Palli On BEST ANSWER

I got it working using single DispatchGroup. This is my delegate method implementation:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    picker.dismiss(animated: true) // dismiss a picker
    
    let imageItems = results
        .map { $0.itemProvider }
        .filter { $0.canLoadObject(ofClass: UIImage.self) } // filter for possible UIImages
    
    let dispatchGroup = DispatchGroup()
    var images = [UIImage]()
    
    for imageItem in imageItems {
        dispatchGroup.enter() // signal IN
        
        imageItem.loadObject(ofClass: UIImage.self) { image, _ in
            if let image = image as? UIImage {
                images.append(image)
            }
            dispatchGroup.leave() // signal OUT
        }
    }
    
    // This is called at the end; after all signals are matched (IN/OUT)
    dispatchGroup.notify(queue: .main) {
        print(images)
        // DO whatever you want with `images` array
    }
}
0
Raman Shyniauski On

1 - Did you set your controller as delegate of PHPickerViewController?

To do that, your controller should conform to PHPickerViewControllerDelegate

class ViewController: UIViewController, PHPickerViewControllerDelegate {

And you should set your controller as delegate of PHPickerViewController

pickerController.delegate = self //if you create PHPickerViewController inside your viewController

And then you will get results on this method

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {

2 - If you can't get multiple selection, you can change selection limit of PHPickerConfiguration object that you use with your PHPickerViewController

var confing = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
confing.selectionLimit = 5
let pickerController = PHPickerViewController(configuration: confing)

3 - And then you can work with objects in results array

let identifiers = results.compactMap(\.assetIdentifier)
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: identifiers, options: nil)
0
thaonguyen On

Get list images selected order from PHPickerViewController:

 func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    dismiss(animated: true)
    var images = [UIImage]()
    let dispatchGroup = DispatchGroup()
    var assets: [PHAsset] = []
    let identifiers = results.compactMap(\.assetIdentifier)
    for id in identifiers {
        dispatchGroup.enter()
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil)
        if let result = fetchResult.firstObject {
            assets.append(result)
        }
        dispatchGroup.leave()
    }
    dispatchGroup.notify(queue: .main, execute: { [weak self] in
        for asset in assets {
            if let image = self?.toImage(asset: asset) {
                images.append(image)
            }
        }
        print("Array image: \(images)")
    })
}

func toImage(asset: PHAsset) -> UIImage? {
    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    options.deliveryMode = .highQualityFormat
    options.isSynchronous = true
    
    var result: UIImage? = nil
    manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: options, resultHandler: { (image, _) in
        if let selectedImage = image {
            result = selectedImage
        }
    })
    
    return result
}

Hope to help you guys