Skip to content

Instantly share code, notes, and snippets.

@vahids
Last active April 23, 2019 05:24
Show Gist options
  • Select an option

  • Save vahids/2cba1437ce55587bf6e85d3ac4150bbe to your computer and use it in GitHub Desktop.

Select an option

Save vahids/2cba1437ce55587bf6e85d3ac4150bbe to your computer and use it in GitHub Desktop.
Live camera UIView on Swift 5
//
// CustomeCameraView.swift
// Live Camera View
//
// Created by Vahid Sayad on 4/22/19.
// Copyright © 2019. All rights reserved.
//
import UIKit
import AVFoundation
class CustomeCameraView: UIView {
var captureSession: AVCaptureSession!
var stillImageOutput: AVCapturePhotoOutput!
var imageCaptured: ((_ newImage: UIImage)->Void)?
func start(completion: ((_ error: String?)->Void) ) {
guard captureSession == nil else {
captureSession.startRunning()
return
}
captureSession = AVCaptureSession()
captureSession.sessionPreset = .vga640x480
guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else {
completion("Unable to open front camera!")
return
}
do {
let input = try AVCaptureDeviceInput(device: frontCamera)
stillImageOutput = AVCapturePhotoOutput()
if captureSession.canAddInput(input) && captureSession.canAddOutput(stillImageOutput) {
captureSession.addInput(input)
captureSession.addOutput(stillImageOutput)
}
// Setup Live View
let view = AVCaptureVideoPreviewLayer(session: captureSession)
view.videoGravity = .resizeAspect
view.connection?.videoOrientation = .portrait
self.layer.addSublayer(view)
DispatchQueue.global(qos: .userInitiated).async {
self.captureSession.startRunning()
DispatchQueue.main.async {
view.frame = self.bounds
}
}
} catch let error {
completion(error.localizedDescription)
}
}
func stop() {
guard captureSession != nil else {return}
guard captureSession.isRunning else {return}
self.captureSession.stopRunning()
}
func resume() {
guard self.captureSession != nil else {return}
guard !self.captureSession.isRunning else {return}
self.captureSession.startRunning()
}
func takePhoto() {
let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
stillImageOutput.capturePhoto(with: settings, delegate: self)
}
}
extension CustomeCameraView: AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let imageData = photo.fileDataRepresentation() else {return}
guard let image = UIImage(data: imageData) else {return}
DispatchQueue.main.async {
self.imageCaptured?(image)
}
}
}
@vahids
Copy link
Author

vahids commented Apr 23, 2019

Setup UIView in Storyboard and add constraints,
Set UIView class to CustomeCameraView

imageCaptured clousure to detect Image Capture.
takePhoto method to Take Image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment