0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】UIImagePickerControllerで簡単カメラ連携

Last updated at Posted at 2021-11-19

やりたいこと

カメラで写真を撮影して、その写真をアプリ内で使いたい。

環境

  • Xcode 13.1
  • Swift 5

準備

カメラを使う際は、info.plist の Camera Usage Description を定義しておく必要があります。
スクリーンショット 2021-11-18 18.53.36.png

処理概要

  1. カメラのアクセス権限確認
  2. UIImagePickerController のインスタンス生成、カメラ起動
  3. Delegateで撮影した写真を受け取る

ソースコード

SampleViewController.swift
class SampleViewController: UIViewController {
    /// ボタンタップでカメラを起動する
    @IBAction private func startCamera() {
        // 1. カメラのアクセス権限確認
        self.confirmCameraAuthorizationStatus { isAuthorized in
            if isAuthorized {
                let sourceType = UIImagePickerController.SourceType.camera
                guard UIImagePickerController.isSourceTypeAvailable(sourceType) else {
                    return
                }
            
                // 2. UIImagePickerController のインスタンス生成、カメラ起動
                let cameraPicker = UIImagePickerController()
                cameraPicker.sourceType = sourceType
                cameraPicker.delegate = self
                self.present(cameraPicker, animated: true, completion: nil)
            }
        }
    }

    /// カメラの利用許可確認
    private func confirmCameraAuthorizationStatus(result: @escaping (Bool) -> Void) {
        // カメラの利用が許可されているか確認
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            result(true)
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { isGranted in
                DispatchQueue.main.async {
                    result(isGranted)
                }
            }
        case .denied, .restricted:
            result(false)
        @unknown default:
            result(false)
        }
    }
}

extension SampleViewController: UIImagePickerControllerDelegate {
    // 3. Delegateで撮影した写真を受け取る
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let pickedImage = info[.originalImage] as? UIImage else {
            print("写真取得失敗")
            picker.dismiss(animated: true, completion: nil)
            return
        }
        
        picker.dismiss(animated: true, completion: nil)
        // pickedImageを使って何か処理をする
    }
}

extension SampleViewController: UINavigationControllerDelegate {    
}

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?