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.

8 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. Nice it seems to be good post... It will get readers engagement on the article since readres engagement plays an vital role in every blog.. i am expecting more updated posts from your hands.
    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
  3. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    Mobile App Development Company in Chennai
    Android app Development Company in Chennai
    ios app development Company in Chennai

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

    ReplyDelete
  5. 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

  6. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    Android App Development Company

    ReplyDelete
  7. 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
  8. great and nice blog thanks sharing..I just want to say that all the information you have given here is awesome...Thank you very much for this one.
    web design Company
    web development Company
    web design Company in chennai
    web development Company in chennai
    web design Company in India
    web development Company in India

    ReplyDelete