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を参考にして指定してください。