Skip to content

Instantly share code, notes, and snippets.

@anupamchugh
Last active June 2, 2020 11:10
Show Gist options
  • Save anupamchugh/9a90bfed10bdafb08d6ed61a7cbad69f to your computer and use it in GitHub Desktop.
Save anupamchugh/9a90bfed10bdafb08d6ed61a7cbad69f to your computer and use it in GitHub Desktop.
import AVFoundation
import UIKit
class CameraVC: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
//custom delegate we've created
var delegate: EmojiFoundDelegate?
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
private let videoDataOutput = AVCaptureVideoDataOutput()
var emojiString = ""
convenience init(emoji: String) {
self.init()
self.emojiString = emoji
}
override func viewDidLoad() {
super.viewDidLoad()
captureSession = AVCaptureSession()
guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return }
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch { return }
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
}
self.videoDataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_32BGRA)] as [String : Any]
self.videoDataOutput.alwaysDiscardsLateVideoFrames = true
self.videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "camera_frame_processing_queue"))
self.captureSession.addOutput(self.videoDataOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = self.view.frame
previewLayer.videoGravity = .resizeAspectFill
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "camera_frame_processing_queue"))
if captureSession?.isRunning == false {
captureSession.startRunning()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if captureSession?.isRunning == true {
captureSession.stopRunning()
}
}
override var prefersStatusBarHidden: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment