UIImagePickerController 経由でカメラや写真アルバムにアクセスすることができますが、 もっと柔軟にカメラを利用するには AVFoundation フレームワークを使います。
ViewController.swiftに追加するコード(赤字部分) |
import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var myImageView: UIImageView! var myImageOutput: AVCaptureStillImageOutput! @IBAction func tapPhoto(sender: AnyObject) { let myAVConnection = myImageOutput.connectionWithMediaType(AVMediaTypeVideo) myImageOutput.captureStillImageAsynchronouslyFromConnection(myAVConnection, completionHandler: { (imageDataBuffer,error) -> Void in let myImageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataBuffer) self.myImageView.image = UIImage(data: myImageData) }) } func startVideo() { let mySession = AVCaptureSession() mySession.sessionPreset = AVCaptureSessionPresetHigh var myCamera: AVCaptureDevice! let devices = AVCaptureDevice.devices() for device in devices { if (device.position == AVCaptureDevicePosition.Back) { myCamera = device as! AVCaptureDevice } } do { let videoInput = try AVCaptureDeviceInput(device: myCamera) mySession.addInput(videoInput) myImageOutput = AVCaptureStillImageOutput() mySession.addOutput(myImageOutput) let myVideoLayer = AVCaptureVideoPreviewLayer(session: mySession) myVideoLayer.frame = view.bounds myVideoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill view.layer.insertSublayer(myVideoLayer,atIndex:0) mySession.startRunning() } catch let error as NSError { print("cannot use camera \(error)") } } override func viewDidLoad() { super.viewDidLoad() startVideo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } |