タイトルの通り、
今回はUIImagePickerControllerでカメラ機能とアルバム機能の実装をしていきます。
『UIImagePickerController』とは
カメラ機能やアルバム(フォトライブラリ)を使用する際によく使用するものです。
ペーペーの僕には謎に包まれている範囲です。正直よくわかりません。
カメラ機能はUIImagePickerController以外にもAVFoundationを使用する実装方法はありますが、
UIImagePickerControllerの方が簡単です。
一つ注意点があります!
このカメラ機能は実機(iPhone)がないと試すことができません!
project作成
今回は『ImagePickerCameraApp』
という名前でプロジェクトを作成します。
まずはStoryboardを開きましょう。
デフォルトで配置してあるViewControllerに
UIImageViewを一つ
UIButtonを二つ
配置してください。
だいたいこんな感じにしましょう。

ついでに2つのUIButtonのテキストを変更しましょう。
- 『camera』・・・カメラを起動するボタン
- 『album』・・・アルバムを起動するボタン
こんな感じにしました。
コードの記述はこんな感じです。
import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.imageView.image = image UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) self.dismiss(animated: true, completion: nil) } @IBAction func launchCamera(sender: UIButton) { // カメラ起動! let camera = UIImagePickerControllerSourceType.camera if UIImagePickerController.isSourceTypeAvailable(camera) { let picker = UIImagePickerController() picker.sourceType = camera picker.delegate = self self.present(picker, animated: true, completion: nil) } } @IBAction func albumButton(_ sender: UIButton) { // アルバム起動! let album = UIImagePickerControllerSourceType.photoLibrary if UIImagePickerController.isSourceTypeAvailable(album) { let album = UIImagePickerController() album.delegate = self album.sourceType = UIImagePickerControllerSourceType.photoLibrary album.allowsEditing = true self.present(album, animated: true, completion: nil) } } }
ABOUT ME