LoginSignup
9

More than 5 years have passed since last update.

【iosアプリ開発メモ】カメラを起動させる

Last updated at Posted at 2018-05-05

すること

ボタンを押すとカメラが起動する

環境

  • macOS High Sierra バージョン 10.13.4
  • Xcode version 9.3
  • swift4

やってみる

1.ボタンを設置する

Main.storybordのViewの中にbuttonを設置する

2.ボタンとコードを関連付ける

  1. Main.storybordに設置したbuttonを選択。
  2. Controlキーを押しながらドラッグして、 ViewController.swiftのViewControllerクラスの中で離す。
  3. ConnectionはドロップダウンからActionを選択。
    Nameに任意の名前を入力。今回は「camera」にする。
    TypeはドロップダウンからUIButtonを選択。
  4. @IBAction func camera(_ sender: UIButton)のような関数が作成されたらOK。

3.コードを書いていく

さっき作られた関数の中にコードを書いていく。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //↓追記した部分
    //対応したボタンが押された時の動作を記述
    @IBAction func camera(_ sender: UIButton) {
        //インスタンス作成
        let pickerController = UIImagePickerController()

        //ソースタイプを指定(cameraの場合はplistでカメラ使用を許可すること)
        pickerController.sourceType = .camera

        //カメラを表示
        present(pickerController, animated: true, completion: nil)

    }

}

コードを書いたらplistでカメラの使用を許可しておく。

ポイント

UIImagePickerController

UIKitに入ってるクラス。

ユーザーのメディアライブラリから画像を撮影し、ムービーを記録し、アイテムを選択するためのシステムインタフェースを管理するビューコントローラ。(公式より翻訳)

UIImagePickerControllerSourceType

UIImagePickerControllerインスタンスのプロパティ

Pickerインターフェイスを実行する前に、この値を目的のソースタイプに設定します。設定するソースタイプは使用可能でなければならず、そうでない場合は例外がスローされます。ピッカーが表示されているときにこのプロパティを変更すると、このプロパティの新しい値と一致するようにピッカーインターフェイスが変更されます。(公式より翻訳)

present

UIViewControllerクラスのインスタンスメソッド。
第一引数に指定したViewControllerを表示してくれる。

終わり

以上、とりあえず起動だけ。

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
9