その後のその後

iOSエンジニア 堤 修一のブログ github.com/shu223

【その1】UIImagePickerController を使わないカメラアプリの実装方法

「カメラ機能をアプリにつけたいけどシャッター音を鳴らしたくない」とか、「カメラ起動時のアニメーションが嫌だ」とかの場合は、UIImagePickerController を使うのではなく AVFoundation フレームワークを使ってカメラ機能を自作する必要があります。


といってもものすごく低レイヤからゴリゴリごにょごにょしなきゃいけないわけじゃなくて、ある程度わかりやすくラップされてるので、CoreXXXX系のフレームワークやOpenGLほどとっつきにくくはなさそうです。


以下はプレビュー表示できるところまでの手順になります。シャッター機能もデータ保存機能も省いてて、細かい設定もしてないので、これが一番シンプルな最低限の形かと思われます

準備

必要なフレームワークをプロジェクトに追加
  • AVFoundation.framework
Info.plist編集

Required device capabilities (UIRequiredDeviceCapabilities) に以下のキーを使う機能に応じて指定

  • still-camera
  • auto-focus-camera
  • front-facing- camera
  • camera-flash
  • video-camera

実装

// カメラデバイスの初期化
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

// 入力の初期化
NSError *error = nil;
AVCaptureInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice
                                                                   error:&error];


if (videoInput) {
    
    // セッション初期化
    AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
    [captureSession addInput:videoInput];
    [captureSession beginConfiguration];
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto;
    [captureSession commitConfiguration];
    
    // プレビュー表示
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
    previewLayer.automaticallyAdjustsMirroring = NO;
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    previewLayer.frame = self.view.bounds;
    [previewCtr.view.layer insertSublayer:previewLayer atIndex:0];

    // セッション開始
    [captureSession startRunning];
}
// エラー
else {
    NSLog(@"ERROR:%@", error);
}