Swift UIImagePickerControllerでフォトアルバム、カメラアクセスを行う

個人開発したアプリの宣伝
目的地が設定できる手帳のような使い心地のTODOアプリを公開しています。
Todo with Location

Todo with Location

  • Yoshiko Ichikawa
  • Productivity
  • Free

スポンサードリンク

info.plist

必要に応じて以下のパーミッションをinfo.plistに記述する。

  • Privacy - Photo Library Additions Usage Description
    • フォトアルバムに画像を保存
  • Privacy - Photo Library Usage Description
    • フォトアルバムにアクセス (不要っぽい?)
  • Privacy - Camera Usage Description
    • カメラアクセス
フォトアルバムにアクセスする

ソースタイプ、UIImagePickerController.SourceType.photoLibraryでアクセスできる。

let sourceType = UIImagePickerController.SourceType.photoLibrary
if UIImagePickerController.isSourceTypeAvailable(sourceType) {
    let cameraPicker = UIImagePickerController()
    cameraPicker.sourceType = sourceType
    cameraPicker.delegate = self    //(1)
    self.present(cameraPicker, animated: true, completion: nil)
}
  1. 画像選択した時の処理はdelegateに記述する。
カメラにアクセスする

ソースタイプ、UIImagePickerController.SourceType.cameraでアクセスできる。

ソースタイプ以外の記述はアルバムと一緒。

let sourceType = UIImagePickerController.SourceType.camera
if UIImagePickerController.isSourceTypeAvailable(sourceType) {  //(1)
    let cameraPicker = UIImagePickerController()
    cameraPicker.sourceType = sourceType
    cameraPicker.delegate = self
    self.present(cameraPicker, animated: true, completion: nil)
}
  1. このタイミングで最初の一度だけ許諾ダイアログが表示される。
フォトアルバムに画像を保存する

UIImageWriteToSavedPhotosAlbumを使用する。呼び出しのタイミングで最初の一度だけ許諾ダイアログが表示される。

UIImageWriteToSavedPhotosAlbum(UIImage(name: "imageData..."), self, nil, nil)
画像選択、カメラ撮影後の処理を定義する

UIImagePickerControllerDelegatedidFinishPickingMediaWithInfoに記述する。

下記では新たにフォトアルバムに選択/撮影された画像を保存する処理を

class InstaCloneViewController: UIViewController, UIImagePickerControllerDelegate {

...func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        //選択された画像はinfo[UIImagePickerController.InfoKey.originalImage] でアクセスできる
        if let pickerImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
            //doAction
        }
        //UIImagePickerControllerを閉じる
        picker.dismiss(animated: true, completion: nil)
    }
}