Created
January 28, 2020 09:13
-
-
Save CyberBison/52a61ae8c28bd5ee789638dbab1be8f2 to your computer and use it in GitHub Desktop.
Simple camera controller to show the front camera in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CameraController: NSObject{ | |
var captureSession: AVCaptureSession? | |
var frontCamera: AVCaptureDevice? | |
var frontCameraInput: AVCaptureDeviceInput? | |
var previewLayer: AVCaptureVideoPreviewLayer? | |
enum CameraControllerError: Swift.Error { | |
case captureSessionAlreadyRunning | |
case captureSessionIsMissing | |
case inputsAreInvalid | |
case invalidOperation | |
case noCamerasAvailable | |
case unknown | |
} | |
func prepare(completionHandler: @escaping (Error?) -> Void){ | |
func createCaptureSession(){ | |
self.captureSession = AVCaptureSession() | |
} | |
func configureCaptureDevices() throws { | |
let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front) | |
self.frontCamera = camera | |
try camera?.lockForConfiguration() | |
camera?.unlockForConfiguration() | |
} | |
func configureDeviceInputs() throws { | |
guard let captureSession = self.captureSession else { throw CameraControllerError.captureSessionIsMissing } | |
if let frontCamera = self.frontCamera { | |
self.frontCameraInput = try AVCaptureDeviceInput(device: frontCamera) | |
if captureSession.canAddInput(self.frontCameraInput!) { captureSession.addInput(self.frontCameraInput!)} | |
else { throw CameraControllerError.inputsAreInvalid } | |
} | |
else { throw CameraControllerError.noCamerasAvailable } | |
captureSession.startRunning() | |
} | |
DispatchQueue(label: "prepare").async { | |
do { | |
createCaptureSession() | |
try configureCaptureDevices() | |
try configureDeviceInputs() | |
} | |
catch { | |
DispatchQueue.main.async{ | |
completionHandler(error) | |
} | |
return | |
} | |
DispatchQueue.main.async { | |
completionHandler(nil) | |
} | |
} | |
} | |
func displayPreview(on view: UIView) throws { | |
guard let captureSession = self.captureSession, captureSession.isRunning else { throw CameraControllerError.captureSessionIsMissing } | |
self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) | |
self.previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill | |
self.previewLayer?.connection?.videoOrientation = .portrait | |
view.layer.insertSublayer(self.previewLayer!, at: 0) | |
self.previewLayer?.frame = view.frame | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment