4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】UIImagePickerより便利なUIPHPickerViewControllerを使ってみた

Posted at

UIImagePickerControllerについて調べていると、PHPickerViewControllerというものに出会ったので使ってみた。

デモ

見た目の動きとしては、ほぼUIImagePickerControllerとほぼ同じです。
イメージ.GIF

UIImagePickerControllerとの違い

・検索機能付き
・複数選択が可能
・プライバシーに配慮したプロセスになっており、Privacy Photolibrary Usageを設定する必要がない

使ってみる

①PhotosUIをインポート

import PhotosUI

②コンフィギュレイションを設定し、PHPickerViewController(configuration:)に値を入れる

var configuration = PHPickerConfiguration()
        
        //選択できる枚数を指定する。 0 を代入すると無制限に選択出来る
        configuration.selectionLimit = 1
        
        //PHPickerViewに何を表示させるか選択出来る。 以下は画像のみ
        configuration.filter = .images
        
        //複数選択したい場合は、配列で選択が可能
        //configuration.filter = .any(of: [.images, .livePhotos, .videos])
        
        let phPicker = PHPickerViewController(configuration: configuration)

③あとは、delegateを設定して表示するだけ

        phPicker.delegate = self
        present(phPicker, animated: true)

画像が選択された時のdelegate処理を書いてみる

extension ViewController: PHPickerViewControllerDelegate {
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        
        //結果から最初のItemProviderを取得
        let itemProvider = results.first?.itemProvider
        
        //オプショナルバインディングで取得したItemProviderのnilチェックとロード可能かチェック
        if let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
            
            //ItemProviderから画像を呼び出す
            itemProvider.loadObject(ofClass: UIImage.self) { (readingImage, error) in
                if let error = error {
                    print("画像の取得に失敗しました:", error)
                    return
                }
                DispatchQueue.main.async {
                    guard let image = readingImage as? UIImage else { return }
                    self.imageView.image = image
                }
            }
        }
    }

参考

UIImagePickerControllerに代わるPHPickerViewControllerの紹介
とても分かりやすく詳しく書かれており、とても参考になりました🙇‍♂️

謎のエラー

シュミレーターでは問題なく動作したが、実機でPHPickerViewを使用したところ、
[ERROR] Could not create a bookmark: NSError: Cocoa 257 "The file couldn’t be opened because you don’t have permission to view it."
というエラーが出た。

エラーをこちらで[PHPicker] Permission error調べたところ

この問題を認識しており、将来のリリースで修正される予定です。
とのことです。

まぁ、動作はするからいいのか?

まとめ

奥が深いPHPImagePickerでした。今後の開発に活用していきたい。

何か間違いがありましたら、優しく教えていただけると幸いです。

4
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?