Categories: Swift

【Swift】PHPickerViewControllerで写真を取得

環境:Swift5 iOS14

写真の取得

preferredAssetRepresentationMode = .current

上記のコードがないとHEICが取得できません

UIImageではなくData型で取得しています

import UIKit
import PhotosUI

class ViewController: UIViewController , PHPickerViewControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var config = PHPickerConfiguration()
        config.filter = .images
        config.preferredAssetRepresentationMode = .current
        config.selectionLimit = 0
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = self
        self.present(picker, animated: true, completion: nil)
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {

        picker.dismiss(animated: true , completion: nil)
        guard let first = results.first else {
            return
        }
        if first.itemProvider.canLoadObject(ofClass: UIImage.self) {
            first.itemProvider.loadDataRepresentation(forTypeIdentifier: "public.image", completionHandler: { (data,error) in
                if let imageData = data {
                    print("imageData = \(imageData)")
                }else{
                    print("error:\(String(describing: error?.localizedDescription))")
                }
            })
        } else {
            print("Error(2)")
        }
    }
}
Pype