PHPickerViewController Disregards Order Photo is Selected

I use a PHPickerViewController to select profile images and want the first photo selected to be a user’s hero image.

Whenever I return the selected results, the order in which I selected is not reflected.

I’ve double checked my config and looked at existing SO answers, but no solution has worked and would appreciate any guidance that does not involve using a 3rd party!

//Setup code

var config = PHPickerConfiguration()    
config.selectionLimit = 3
    config.filter = .images
    config.selection = .ordered
    
    let picker = PHPickerViewController(configuration: config)
    picker.delegate = self

//Delegate handler

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
                
guard !results.isEmpty else {
    picker.dismiss(animated: true)
    return
}

self.photos = []

var tempImages: [Int: UIImage] = [:]
let dispatchGroup = DispatchGroup()

for (index, result) in results.enumerated() {
     
     dispatchGroup.enter() // Enter the group

     result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] object, error in
         defer { dispatchGroup.leave() }

         guard let self = self else { return }

         if let image = object as? UIImage {
             
             tempImages[index] = image
         }
     }
 }

dispatchGroup.notify(queue: .main) { [weak self] in
                            
    guard let self = self else { return }
    
    for index in 0..<tempImages.keys.count {
        
        if let image = tempImages[index] {
                                
            self.photos?.append(image)
        }
    }
}
        
picker.dismiss(animated: true)

}

Leave a Comment