4
2

More than 1 year has passed since last update.

PHPickerViewControllerから直にData型の画像データを取得するには?

Last updated at Posted at 2020-09-28

PHPickerViewController

AppleのPHPickerViewControllerのサンプルコード を見ると、UIImageを取得する例は書かれているのですが、Dataを取得する例はありません。

当然ながらUIImageをDataに変換するのは微妙です。

なぜならGIFを選択した場合、アニメーションが止まってしまうためです(UIImageをDataに変換するメソッドは「pngData()」と「jpegData(compressionQuality:)」の2つしかなくGIF用のものは存在しません)。

というわけで、やはり直でData型を取得したい。

そんな人に向けて、 PHPickerViewControllerからDataを取得する方法 を書いておきます。

NSItemProviderのloadDataRepresentation(forTypeIdentifier:completionHandler:)を使えば画像のDataを取得できる

NSItemProviderの loadDataRepresentation(forTypeIdentifier:completionHandler:) を使えば取得できます。

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    results.forEach { result in
        result.itemProvider.loadDataRepresentation(forTypeIdentifier: "public.image", completionHandler: { [weak self] data, _ in
            guard let data = data else { return }
            print(data)
        })
    }
}

ミソとしては、forTypeIdentifier(Uniform Type Identifier)に public.image を指定することですね。
こうすることで、HEICやPNG、JPG、GIFなどのDataを取得できます。

もっと、取得するDataを細かく指定したい場合は、Appleの Uniform Type Identifier Conceptsを参考にして指定してください。

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