LoginSignup
3
3

More than 3 years have passed since last update.

PHPickerViewControllerを使ってみた

Last updated at Posted at 2020-07-13

はじめに

PHPickerViewControllerはUIImagePickerControllerのカメラ以外の機能に複数選択など新機能が追加されました。
そのPHPickerViewControllerを使ったサンプルコードを作ってみました。
Xcode12 beta2で作成しています。
サンプルコードはgithubで公開しています。

コードの解説

呼び出し

    func makeUIViewController(context: Context) -> some UIViewController {
        var configuration = PHPickerConfiguration()
        // 静止画を選択
        configuration.filter = .images
        // 複数選択可能(上限枚数なし)
        configuration.selectionLimit = 0
        let picker = PHPickerViewController(configuration: configuration)
        picker.delegate = context.coordinator
        return picker
    }

filterで選択できる画像形式を指定できます。複数選択もできるうようです。
selectionLimitで複数選択する時の上限を指定できます。0の場合は上限なく複数選択できます。

delegate

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

            // Pickerを閉じる
            parent.picker.toggle()

            for result in results {
                if result.itemProvider.canLoadObject(ofClass: UIImage.self) {
                    result.itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in

                        if let image = image as? UIImage {
                            // 選択された画像を追加する
                            self.parent.images.append(image)
                        } else {
                            print("Error(1)")
                        }

                    }
                } else {
                    print("Error(2)")
                }
            }
        }

画像を選択後Addを押すとdelegateが呼ばれます。
UIImageに変換し、クロージャーが呼ばれます。シュミレーターで選択した一部の画像はUIImageに変換できないことがありました。
これは、まだBetaなので今後正式リリースに向けて改善されるのだと期待しています。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3