Skip to content

Instantly share code, notes, and snippets.

@pardeike
Last active October 15, 2018 10:49
Show Gist options
  • Save pardeike/ebe4b9b189219bd95b9b8bd5536774e4 to your computer and use it in GitHub Desktop.
Save pardeike/ebe4b9b189219bd95b9b8bd5536774e4 to your computer and use it in GitHub Desktop.
VideoPreviewController
import UIKit
import AVFoundation
open class VideoPreview : UIViewController {
var captureSession: AVCaptureSession!
var camera: AVCaptureDevice!
var preview: AVCaptureVideoPreviewLayer!
func initSession() {
captureSession = AVCaptureSession()
captureSession.beginConfiguration()
captureSession.sessionPreset = .high
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back)
camera = discoverySession.devices[0]
try! camera.lockForConfiguration()
camera.focusMode = .continuousAutoFocus
camera.exposureMode = .continuousAutoExposure
camera.unlockForConfiguration()
let cameraInput = try! AVCaptureDeviceInput (device: camera)
captureSession.addInput(cameraInput)
captureSession.commitConfiguration()
preview = AVCaptureVideoPreviewLayer(session: captureSession)
preview.videoGravity = .resizeAspect
}
func updatePreview() {
preview.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.shared.statusBarOrientation.rawValue)!
preview.frame.size = view.frame.size
// debug
print("\(self.preview.connection!.videoOrientation.rawValue)")
}
override open func viewDidLoad() {
super.viewDidLoad()
initSession()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.layer.addSublayer(preview)
updatePreview()
captureSession.startRunning()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
preview.removeFromSuperlayer()
captureSession.stopRunning()
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updatePreview()
}
/*open override var shouldAutorotate: Bool {
return false
}*/
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { context in
self.updatePreview()
})
super.viewWillTransition(to: size, with: coordinator)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment