Tuesday, October 11, 2016

iOS custom camera with Swift 3

This tutorial helps you create a custom iOS camera with overlay in Swift 3.  You can download the completed project here.

Step 1. Create the project, select Single View Application

Step 2. In the ViewController declare the following variables.
       
@IBOutlet weak var navigationBar: UINavigationBar!    
@IBOutlet weak var imgOverlay: UIImageView!    
@IBOutlet weak var btnCapture: UIButton!    

let captureSession = AVCaptureSession()    
let stillImageOutput = AVCaptureStillImageOutput()    
var previewLayer : AVCaptureVideoPreviewLayer?   

Step 3. Update the viewDidLoad() method as follows.

       
     override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        captureSession.sessionPreset = AVCaptureSessionPresetHigh
        
        if let devices = AVCaptureDevice.devices() as? [AVCaptureDevice] {
            // Loop through all the capture devices on this phone
            for device in devices {
                // Make sure this particular device supports video
                if (device.hasMediaType(AVMediaTypeVideo)) {
                    // Finally check the position and confirm we've got the back camera
                    if(device.position == AVCaptureDevicePosition.front) {
                        captureDevice = device
                        if captureDevice != nil {
                            print("Capture device found")
                            beginSession()
                        }
                    }
                }
            }
        }
    }
Step 4. Add the following functions in the ViewController

       
@IBAction func actionCameraCapture(_ sender: AnyObject) {
        
        print("Camera button pressed")
        saveToCamera()
    }
    
    func beginSession() {
        
        do {
            try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            stillImageOutput.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
            
            if captureSession.canAddOutput(stillImageOutput) {
                captureSession.addOutput(stillImageOutput)
            }
            
        }
        catch {
            print("error: \(error.localizedDescription)")
        }
        
        guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else {
            print("no preview layer")
            return
        }
        
        self.view.layer.addSublayer(previewLayer)
        previewLayer.frame = self.view.layer.frame
        captureSession.startRunning()
        
        self.view.addSubview(navigationBar)
        self.view.addSubview(imgOverlay)
        self.view.addSubview(btnCapture)
    }
    
    func saveToCamera() {
        
        if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo) {
            
            stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (CMSampleBuffer, Error) in
                if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(CMSampleBuffer) {
                    
                    if let cameraImage = UIImage(data: imageData) {
                        
                        UIImageWriteToSavedPhotosAlbum(cameraImage, nil, nil, nil)                        
                    }
                }
            })
        }
    }

       
 

Step 5. Update your storyboard as shown in the image and connect the outlets.

Step 6. Hit "Command + R” :)
Once again, feel free to download the completed project here.

5 comments:

  1. Can I include the overlay grid in the resulting photo? How can I do that?
    Excellent code by the way, thanks

    ReplyDelete
  2. thanks a lot, using same in my code.

    ReplyDelete
  3. Can you modify code using AVCapturePhotoOutput in place of AVCaptureStillImageOutput as it is deprecated and i am facing issue with it, it will be a great help.
    Thanks.

    ReplyDelete
  4. The greatest inventions in the world were once thoughts but the inventors experimented on their ideas and came up with inventions that have transformed various processes and systems of the world. This article will not only help the online users to learn programming skills but also experiment their thoughts while Reworking on a Paper.

    ReplyDelete
  5. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Mobile App development Company
    Ios App development Company

    ReplyDelete