0

目前,我正在尝试深入 PHPickerViewController 以从照片中同时选择多个图像。所以我想要用户选择的图像数组,我尝试了太多方法但没有运气。这是我的代码,请告诉我有最佳实践吗?

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)")
                }
            })
        }
    }
4

1 回答 1

2

1 - 您是否将控制器设置为PHPickerViewController的代表?

为此,您的控制器应符合PHPickerViewControllerDelegate

class ViewController: UIViewController, PHPickerViewControllerDelegate {

你应该将你的控制器设置为PHPickerViewController的代表

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

然后你会得到这个方法的结果

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

2 - 如果您无法获得多项选择,您可以更改与 PHPickerViewController 一起使用的PHPickerConfiguration对象的选择限制

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

3 - 然后您可以使用结果数组中的对象

let identifiers = results.compactMap(\.assetIdentifier)
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: identifiers, options: nil)
于 2021-08-27T09:34:51.837 回答