Cómo usar AVCapturePhotoOutput

He estado trabajando en el uso de una camera personalizada, y recientemente me actualicé a Xcode 8 beta junto con Swift 3. Originalmente tuve esto:

var stillImageOutput: AVCaptureStillImageOutput? 

Sin embargo, ahora recibo la advertencia:

'AVCaptureStillImageOutput' quedó en desuso en iOS 10.0: utilice AVCapturePhotoOutput en su lugar

Como esto es bastante nuevo, no he visto mucha información al respecto. Aquí está mi código actual:

 var captureSession: AVCaptureSession? var stillImageOutput: AVCaptureStillImageOutput? var previewLayer: AVCaptureVideoPreviewLayer? func clickPicture() { if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) { videoConnection.videoOrientation = .portrait stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProvider(data: imageData!) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right) } }) } } 

He intentado mirar AVCapturePhotoCaptureDelegate , pero no estoy seguro de cómo usarlo. ¿Alguien sabe cómo usar esto? Gracias.

Hola, es muy fácil usar AVCapturePhotoOutput .

Necesita el AVCapturePhotoCaptureDelegate que devuelve el CMSampleBuffer .

También puede get una vista previa de la image si le indica a AVCapturePhotoSettings la vista previaFormato

 class CameraCaptureOutput: NSObject, AVCapturePhotoCaptureDelegate { let cameraOutput = AVCapturePhotoOutput() func capturePhoto() { let settings = AVCapturePhotoSettings() let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first! let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType, kCVPixelBufferWidthKey as String: 160, kCVPixelBufferHeightKey as String: 160] settings.previewPhotoFormat = previewFormat self.cameraOutput.capturePhoto(with: settings, delegate: self) } func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: NSError?) { if let error = error { print(error.localizedDescription) } if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) { print(image: UIImage(data: dataImage).size) // Your Image } } } 

Para get más información, visite https://developer.apple.com/reference/AVFoundation/AVCapturePhotoOutput

Hay mi implementación completa

 import UIKit import AVFoundation class ViewController: UIViewController, AVCapturePhotoCaptureDelegate { var captureSesssion : AVCaptureSession! var cameraOutput : AVCapturePhotoOutput! var previewLayer : AVCaptureVideoPreviewLayer! @IBOutlet weak var captunetworkingImage: UIImageView! @IBOutlet weak var previewView: UIView! override func viewDidLoad() { super.viewDidLoad() captureSesssion = AVCaptureSession() captureSesssion.sessionPreset = AVCaptureSessionPresetPhoto cameraOutput = AVCapturePhotoOutput() let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) if let input = try? AVCaptureDeviceInput(device: device) { if (captureSesssion.canAddInput(input)) { captureSesssion.addInput(input) if (captureSesssion.canAddOutput(cameraOutput)) { captureSesssion.addOutput(cameraOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSesssion) previewLayer.frame = previewView.bounds previewView.layer.addSublayer(previewLayer) captureSesssion.startRunning() } } else { print("issue here : captureSesssion.canAddInput") } } else { print("some problem here") } } // Take picture button @IBAction func didPressTakePhoto(_ sender: UIButton) { let settings = AVCapturePhotoSettings() let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first! let previewFormat = [ kCVPixelBufferPixelFormatTypeKey as String: previewPixelType, kCVPixelBufferWidthKey as String: 160, kCVPixelBufferHeightKey as String: 160 ] settings.previewPhotoFormat = previewFormat cameraOutput.capturePhoto(with: settings, delegate: self) } // callBack from take picture func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { if let error = error { print("error occure : \(error.localizedDescription)") } if let sampleBuffer = photoSampleBuffer, let previewBuffer = previewPhotoSampleBuffer, let dataImage = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewBuffer) { print(UIImage(data: dataImage)?.size as Any) let dataProvider = CGDataProvider(data: dataImage as CFData) let cgImageRef: CGImage! = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) let image = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right) self.captunetworkingImage.image = image } else { print("some error here") } } // This method you can use somewhere you need to know camera permission state func askPermission() { print("here") let cameraPermissionStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) switch cameraPermissionStatus { case .authorized: print("Already Authorized") case .denied: print("denied") let alert = UIAlertController(title: "Sorry :(" , message: "But could you please grant permission for camera within device settings", prefernetworkingStyle: .alert) let action = UIAlertAction(title: "Ok", style: .cancel, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) case .restricted: print("restricted") default: AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [weak self] (granted :Bool) -> Void in if granted == true { // User granted print("User granted") DispatchQueue.main.async(){ //Do smth that you need in main thread } } else { // User Rejected print("User Rejected") DispatchQueue.main.async(){ let alert = UIAlertController(title: "WHY?" , message: "Camera it is the main feature of our application", prefernetworkingStyle: .alert) let action = UIAlertAction(title: "Ok", style: .cancel, handler: nil) alert.addAction(action) self?.present(alert, animated: true, completion: nil) } } }); } } } 

Encontré este proyecto en GitHub que me ayudó a comprender la initialization del dispositivo y la session de captura.

AVCapturePhotoOutput_test por inoue0426