目的
iOSアプリにて、写真アプリの画像や動画データを取得する実装メモ
環境
- Xcode 11.4
- swift 5
実装メモ
写真アプリのデータを取得する場合はUIImagePickerController
という標準ライブラリを使用します。
まず、Delegate設定
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
UIImagePickerControllerの設定
以下の例では動画だけですが、mediaTypesを[“public.image”, “public.movie”]とすると写真・動画両方表示されます。
var imagePC: UIImagePickerController! = UIImagePickerController()
imagePC.sourceType = .photoLibrary
imagePC.delegate = self
imagePC.mediaTypes = ["public.movie"]
present(imagePC, animated: true, completion: nil)
Delegateのfunction、画像や動画が選択されると呼ばれます。
画像選択の場合は**info[.mediaURL]の部分が、info[.imageURL]**となるかと
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let mediaURL = info[.mediaURL] as? URL
print(mediaURL)
imagePC.dismiss(animated: true)
}
以上です。