Simple Swift class to provide all the configurations you need to create custom camera view in your app

Overview

Camera Manager

CocoaPods Carthage compatible

This is a simple Swift class to provide all the configurations you need to create custom camera view in your app. It follows orientation change and updates UI accordingly, supports front and rear camera selection, pinch to zoom, tap to focus, exposure slider, different flash modes, inputs and outputs and QRCode detection. Just drag, drop and use.

We've also written a blog post about it. You can read it here.

Installation with CocoaPods

The easiest way to install the CameraManager is with CocoaPods

Podfile

use_frameworks!

pod 'CameraManager', '~> 5.1'

Installation with Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code.

Add CameraManager as a dependency in your Package.swift file:

import PackageDescription

let package = Package(
    dependencies: [
        .Package(url: "https://github.com/imaginary-cloud/CameraManager", from: "5.1.3")
    ]
)

Installation with Carthage

Carthage is another dependency management tool written in Swift.

Add the following line to your Cartfile:

github "imaginary-cloud/CameraManager" >= 5.1

And run carthage update to build the dynamic framework.

How to use

To use it you just add the preview layer to your desired view, you'll get back the state of the camera if it's unavailable, ready or the user denied access to it. Have in mind that in order to retain the AVCaptureSession you will need to retain cameraManager instance somewhere, ex. as an instance constant.

let cameraManager = CameraManager()
cameraManager.addPreviewLayerToView(self.cameraView)

To shoot image all you need to do is call:

cameraManager.capturePictureWithCompletion({ result in
    switch result {
        case .failure:
            // error handling
        case .success(let content):
            self.myImage = content.asImage;
    }
})

To record video you call:

cameraManager.startRecordingVideo()
cameraManager.stopVideoRecording({ (videoURL, recordError) -> Void in
    guard let videoURL = videoURL else {
        //Handle error of no recorded video URL
    }
    do {
        try FileManager.default.copyItem(at: videoURL, to: self.myVideoURL)
    }
    catch {
        //Handle error occured during copy
    }
})

To zoom in manually:

let zoomScale = CGFloat(2.0)
cameraManager.zoom(zoomScale)

Properties

You can set input device to front or back camera. (Default: .Back)

cameraManager.cameraDevice = .front || .back

You can specify if the front camera image should be horizontally fliped. (Default: false)

cameraManager.shouldFlipFrontCameraImage = true || false

You can enable or disable gestures on camera preview. (Default: true)

cameraManager.shouldEnableTapToFocus = true || false
cameraManager.shouldEnablePinchToZoom = true || false
cameraManager.shouldEnableExposure = true || false

You can set output format to Image, video or video with audio. (Default: .stillImage)

cameraManager.cameraOutputMode = .stillImage || .videoWithMic || .videoOnly

You can set the quality based on the AVCaptureSession.Preset values (Default: .high)

cameraManager.cameraOutputQuality = .low || .medium || .high || *

* check all the possible values here

You can also check if you can set a specific preset value:

if .cameraManager.canSetPreset(preset: .hd1280x720) {
     cameraManager.cameraOutputQuality = .hd1280x720
} else {
    cameraManager.cameraOutputQuality = .high
}

You can specify the focus mode. (Default: .continuousAutoFocus)

cameraManager.focusMode = .autoFocus || .continuousAutoFocus || .locked

You can specifiy the exposure mode. (Default: .continuousAutoExposure)

cameraManager.exposureMode = .autoExpose || .continuousAutoExposure || .locked || .custom

You can change the flash mode (it will also set corresponding flash mode). (Default: .off)

cameraManager.flashMode = .off || .on || .auto

You can specify the stabilisation mode to be used during a video record session. (Default: .auto)

cameraManager.videoStabilisationMode = .auto || .cinematic

You can get the video stabilization mode currently active. If video stabilization is neither supported or active it will return .off.

cameraManager.activeVideoStabilisationMode

You can enable location services for storing GPS location when saving to Camera Roll. (Default: false)

cameraManager.shouldUseLocationServices = true || false

In case you use location it's mandatory to add NSLocationWhenInUseUsageDescription key to the Info.plist in your app. More Info

For getting the gps location when calling capturePictureWithCompletion you should use the CaptureResult as data (see Example App).

You can specify if you want to save the files to phone library. (Default: true)

cameraManager.writeFilesToPhoneLibrary = true || false

You can specify the album names for image and video recordings.

cameraManager.imageAlbumName =  "Image Album Name"
cameraManager.videoAlbumName =  "Video Album Name"

You can specify if you want to disable animations. (Default: true)

cameraManager.animateShutter = true || false
cameraManager.animateCameraDeviceChange = true || false

You can specify if you want the user to be asked about camera permissions automatically when you first try to use the camera or manually. (Default: true)

cameraManager.showAccessPermissionPopupAutomatically = true || false

To check if the device supports flash call:

cameraManager.hasFlash

To change flash mode to the next available one you can use this handy function which will also return current value for you to update the UI accordingly:

cameraManager.changeFlashMode()

You can even setUp your custom block to handle error messages: It can be customized to be presented on the Window root view controller, for example.

cameraManager.showErrorBlock = { (erTitle: String, erMessage: String) -> Void in
    var alertController = UIAlertController(title: erTitle, message: erMessage, preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: { (alertAction) -> Void in
    }))

    let topController = UIApplication.shared.keyWindow?.rootViewController

    if (topController != nil) {
        topController?.present(alertController, animated: true, completion: { () -> Void in
            //
        })
    }

}

You can set if you want to detect QR codes:

cameraManager.startQRCodeDetection { (result) in
    switch result {
    case .success(let value):
        print(value)
    case .failure(let error):
        print(error.localizedDescription)
    }
}

and don't forget to call cameraManager.stopQRCodeDetection() whenever you done detecting.

Support

Supports iOS 9 and above. Xcode 11.4 is required to build the latest code written in Swift 5.2.

Now it's compatible with latest Swift syntax, so if you're using any Swift version prior to 5 make sure to use one of the previously tagged releases:

License

Copyright © 2010-2020 Imaginary Cloud. This library is licensed under the MIT license.

About Imaginary Cloud

Imaginary Cloud

At Imaginary Cloud, we build world-class web & mobile apps. Our Front-end developers and UI/UX designers are ready to create or scale your digital product. Take a look at our website and get in touch! We'll take it from there.

Comments
  • Back camera opened when front was set

    Back camera opened when front was set

    I setup the cameraManager as follows, and the back camera was presented in the preview layer instead of the front camera. This only happened one time.

    CameraManager.sharedInstance.addPreviewLayerToView(self.previewView!) CameraManager.sharedInstance.cameraDevice = .Front CameraManager.sharedInstance.cameraOutputMode = .StillImage CameraManager.sharedInstance.cameraOutputQuality = .High

    bug 
    opened by tonacy 11
  • Camera freezes

    Camera freezes

    the same error on 4.40 version and iOS 12 models

    PID: 3732, TID: 1376881, Thread name: com.apple.CoreMotion.MotionThread, Queue name: com.apple.root.default-qos.overcommit, QoS: 0 Backtrace: 4 libobjc.A.dylib 0x000000018108f534 + 56 5 CoreMotion 0x0000000187918040 CoreMotion + 307264 6 CoreMotion 0x0000000187918574 CoreMotion + 308596 7 CoreMotion 0x0000000187918484 CoreMotion + 308356 8 CoreMotion 0x0000000187949c64 CoreMotion + 511076 9 CoreMotion 0x0000000187949cc4 CoreMotion + 511172 10 CoreFoundation 0x0000000181e28354 + 28 11 CoreFoundation 0x0000000181e27c38 + 276 12 CoreFoundation 0x0000000181e22f14 + 2324 13 CoreFoundation 0x0000000181e222e8 CFRunLoopRunSpecific + 452 14 CoreFoundation 0x0000000181e2304c CFRunLoopRun + 84 15 CoreMotion 0x00000001879495fc CoreMotion + 509436 16 libsystem_pthread.dylib 0x0000000181a9c974 + 132 17 libsystem_pthread.dylib 0x0000000181a9c8d0 _pthread_start + 52 18 libsystem_pthread.dylib 0x0000000181aa4ddc thread_start + 4

    opened by SandrikaJanjghava 10
  • Is there any way possible to clone the camera feed from CameraManager?

    Is there any way possible to clone the camera feed from CameraManager?

    Just for display purposes, I would like to clone the camera feed to multiple UIView objects at the same time. It could be fun to display two or more identical camera feeds that appear synced! Any cloned feeds would not need to have video recording capability. Please see https://stackoverflow.com/questions/61295613/is-there-a-way-to-copy-a-uiview-objects-video-content-into-a-second-uiview-im Does anyone know if there is a way to clone them in my own code? Or could there by an internal array kept inside the pod that would allow clones (with no recording capability)?

    opened by MichaelKucinski 8
  • _getMovieOutput() causing crash when orientation is changed specifically on iPhone6 and iPhone 6s

    _getMovieOutput() causing crash when orientation is changed specifically on iPhone6 and iPhone 6s

    The error only occurs on iPhone6 and 6s and happens kind of randomly, after an initial crash for a user it will most likely not happen again.

    see thread below

    Fatal Exception: NSInvalidArgumentException *** -[AVCaptureSession addOutput:] An AVCaptureOutput instance may not be added to more than one session

    0 CoreFoundation 0x1c8088ec4 __exceptionPreprocess 1 libobjc.A.dylib 0x1c7259a40 objc_exception_throw 2 AVFoundation 0x1ce18151c -[AVCaptureSession addOutput:] 3 CameraManager 0x1015a9ad4 specialized CameraManager._getMovieOutput() (CameraManager.swift:1162) 4 CameraManager 0x1015a1dd4 CameraManager._orientationChanged() (CameraManager.swift:1193) 5 CameraManager 0x1015b0f20 partial apply for closure 1 in CameraManager._startFollowingDeviceOrientation() ()

    opened by kselvin 8
  • stopVideoRecording not working

    stopVideoRecording not working

    Hi Guys,

    i am trying to build a camera app and i want to start stop the record with the same IBAction.

    override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            cameraManager.addPreviewLayerToView(previewLayerOutlet)
            cameraManager.cameraDevice = .back
            cameraManager.cameraOutputMode = .videoWithMic
            cameraManager.cameraOutputQuality = .medium
            cameraManager.writeFilesToPhoneLibrary = true
            cameraManager.showAccessPermissionPopupAutomatically = true
        }
    
    @IBAction func startVideoRecording(_ sender: UIButton) {
            if sender.isSelected {
                cameraManager.stopVideoRecording({ (videoURL, error) -> Void in
                    print(videoURL!.absoluteString)
                })
            }else{
                cameraManager.startRecordingVideo()
            }
            sender.isSelected = !sender.isSelected
        }
    

    But

    print(videoURL!.absoluteString) 
    

    never called. Any hint what I did wrong :/

    Thanks

    opened by appcelerate 8
  • Crash when trying to record video

    Crash when trying to record video

    When I call CameraManager.sharedInstance.startRecordingVideo(), my app crashes with the following error: -[AVCaptureMovieFileOutput startRecordingToOutputFileURL:recordingDelegate:] - no active/enabled connections.'

    opened by mrbaker4 8
  • imageCompletion called twice for capturePictureWithCompletion with .writeFilesToPhoneLibrary = true

    imageCompletion called twice for capturePictureWithCompletion with .writeFilesToPhoneLibrary = true

    Hey,

    It turns out that when you set

    cameraManager.writeFilesToPhoneLibrary = true
    

    and then call

    cameraManager.capturePictureWithCompletion {}
    

    The imageCompletion closure get called twice.

    Here is a workaround t'ill it's fixed

    cameraManager.capturePictureWithCompletion { [weak self] result in
       guard let `self` = self else { return }
       switch result {
          case .success(let content):
            switch content {
              case .image(let photo):
                // update your layout ....
              default: break
             }
           case .failure(let error):
              // Handle error
        }
    }
    

    switching over content and using .image case let ou get notified once per image captured, but if you need to use the .asset case then you'll get notified twice.

    opened by franckclement 6
  • Change callbacks to the swifty way of reporting success and errors.

    Change callbacks to the swifty way of reporting success and errors.

    Change callbacks to use enums to report success/failure. This makes it possible to add reporting the PHAsset result of storing an image to the photo library.

    It might be better to put the enums in a separate file... I can do that if needed.

    opened by jpalten 6
  • Deinit cause crash when `cameraDevice = .front`

    Deinit cause crash when `cameraDevice = .front`

    Hi, seems like the self.cameraDevice = .back inside stopAndRemoveCaptureSession() in deinit is causing crash if the cameraDevice is .front, I have to manually calling stopAndRemoveCaptureSession() in my viewController to stop it before dismiss the viewController.

    Please check this issue, thank you.

    opened by TienVu-PW 6
  • I found BUGS.

    I found BUGS.

    1. Default output is .stillImage, Default Flash to .off
    2. Set Flash to .on
    3. Change the output to .videoWithMic
    4. Change the device camera to .back
    5. Record a video

    Bugs: Recorded video doesn't have sound(sound works fine with front device) Flash/Torch Doesn't work.

    opened by Marlunes 6
  • when view goes to background , capture session is getting nil and stop recording is not working

    when view goes to background , capture session is getting nil and stop recording is not working

    can anybody tell, why this is happening , when view goes to background , capture session is getting nil and stop recording is not working

    i just debug the issue and found that open func fileOutput(_ captureOutput: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) is giving error

    Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo={NSLocalizedDescription=Recording Stopped, AVErrorRecordingSuccessfullyFinishedKey=true, NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., NSUnderlyingError=0x1c084c1e0 {Error Domain=NSOSStatusErrorDomain Code=-16414 "(null)"}}

    opened by chiragkukreja 5
  • Feature: Add the ability to enable video mirroring on front-facing camera output

    Feature: Add the ability to enable video mirroring on front-facing camera output

    It would be really useful to add the ability to enable mirroring on the result of a front-facing camera video capture, because right now is forcefully flipped.

    opened by Samigos 0
  • Can't change camera during video recording

    Can't change camera during video recording

    I am trying to record a video that starts with the back camera and then continues with the back camera. But after tapping the flip camera button during recording, I get an error message:

    Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo={AVErrorRecordingSuccessfullyFinishedKey=true, NSLocalizedDescription=Recording Stopped, NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., AVErrorRecordingFailureDomainKey=1, NSUnderlyingError=0x105d9b3d0 {Error Domain=NSOSStatusErrorDomain Code=-16414 "(null)"}}

    Any idea why switching cameras during video recording causes this error, and what can be done about it?

    Thanks, Joel

    opened by joeldrotleff 0
  • cameraManager.stopVideoRecording doesn't triggering callback

    cameraManager.stopVideoRecording doesn't triggering callback

    Sometimes, cameraManager.stopVideoRecording seems work perfection in lower duration recording, but when try to do more recording then it will not return completion block, it was not going in below condition because runningMovieOutput.isRecording returning false (in CameraManager.swift) and didn't get callback :

    if let runningMovieOutput = movieOutput,
             runningMovieOutput.isRecording {
             videoCompletion = completion
            runningMovieOutput.stopRecording()
    } 
    

    I also tried different ways from given feedback like 1.) Moving cameraManager.cameraOutputMode in the "record" button method just before calling cameraManager.startRecordingVideo() but, this is not working.

    2.) By checking and changing cameraOutputMode before start recording and after stop recording Before start recording : ``` if cameraManager.cameraOutputMode == .stillImage { print("Camera output is stillImage, switching to videoWithMic") cameraManager.cameraOutputMode = .videoWithMic } cameraManager.startRecordingVideo()

    
          _After stop recording :_
    
            ```
    cameraManager.stopVideoRecording { (URL, error) in
                 print("Video Recording URL: ", URL!);
        
                 if cameraManager.cameraOutputMode == .videoWithMic {
                         cameraManager.cameraOutputMode = .stillImage
                 }
            }
    

    I tried above solutions but none of these are working for me. 🙁 I am using CameraManager cocoapod (version 5.1.3)

    Could you please help me out of this issue? Waiting for your response...😌

    opened by hiteshcmarix 0
  • shouldFlipFrontCameraImage doesn't seem to work

    shouldFlipFrontCameraImage doesn't seem to work

    When using the front camera with shouldFlipFrontCameraImage set to true shows the image without being horizontally flipped. Changing it to false doesn't do anything either.

    opened by fischu 0
Owner
Imaginary Cloud
Web and mobile development done right. Excelling at UX and UI design.
Imaginary Cloud
ALCameraViewController - A camera view controller with custom image picker and image cropping.

ALCameraViewController A camera view controller with custom image picker and image cropping. Features Front facing and rear facing camera Simple and c

Alex Littlejohn 2k Dec 6, 2022
Custom camera with AVFoundation. Beautiful, light and easy to integrate with iOS projects.

?? Warning This repository is DEPRECATED and not maintained anymore. Custom camera with AVFoundation. Beautiful, light and easy to integrate with iOS

Tudo Gostoso Internet 1.4k Dec 16, 2022
ScanBarcodes is a SwiftUI view that scans barcodes using an iPhone or iPad camera.

ScanBarcodes ScanBarcodes is a SwiftUI view that scans barcodes using an iPhone or iPad camera. The framework uses AVFoundation for high performance v

NASA Jet Propulsion Laboratory 6 Nov 29, 2022
A light weight & simple & easy camera for iOS by Swift.

DKCamera Description A light weight & simple & easy camera for iOS by Swift. It uses CoreMotion framework to detect device orientation, so the screen-

Bannings 86 Aug 18, 2022
An iOS framework that uses the front camera, detects your face and takes a selfie.

TakeASelfie An iOS framework that uses the front camera, detects your face and takes a selfie. This api opens the front camera and draws an green oval

Abdullah Selek 37 Jan 3, 2023
A simple, customizable camera control - video recorder for iOS.

LLSimpleCamera: A simple customizable camera - video recorder control LLSimpleCamera is a library for creating a customized camera - video recorder sc

Ömer Faruk Gül 1.2k Dec 12, 2022
BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

HyperRedink 1.6k Jan 7, 2023
A camera app we will dive deep into AVFoundation library

Camera App In this project you are going to discover few concepts in Swift that I've been working on for few weeks, Core Animations with CAShape Layer

Dheeraj Kumar Sharma 12 Nov 13, 2022
Instagram-like photo browser and a camera feature with a few line of code in Swift.

Fusuma is a Swift library that provides an Instagram-like photo browser with a camera feature using only a few lines of code.

Yuta Akizuki 2.4k Dec 31, 2022
NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS

NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS. Integration can optionally leverage AVFoundation or ARKit.

NextLevel 2k Jan 2, 2023
Camera engine for iOS, written in Swift, above AVFoundation. :monkey:

?? The most advanced Camera framework in Swift ?? CameraEngine is an iOS camera engine library that allows easy integration of special capture feature

Remi ROBERT 575 Dec 25, 2022
A Snapchat Inspired iOS Camera Framework written in Swift

Overview SwiftyCam is a a simple, Snapchat-style iOS Camera framework for easy photo and video capture. SwiftyCam allows users to capture both photos

Andrew Walz 2k Dec 21, 2022
A camera designed in Swift for easily integrating CoreML models - as well as image streaming, QR/Barcode detection, and many other features

Would you like to use a fully-functional camera in an iOS application in seconds? Would you like to do CoreML image recognition in just a few more sec

David Okun 868 Dec 29, 2022
UIView+CameraBackground - Show camera layer as a background to any UIView.

UIView+CameraBackground Show camera layer as a background to any UIView. Features Both front and back camera supported. Flash modes: auto, on, off. Co

Yonat Sharon 63 Nov 15, 2022
This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system's image library.

title description Camera Take pictures with the device camera. AppVeyor Travis CI cordova-plugin-camera This plugin defines a global navigator.camera

null 0 Nov 2, 2021
A fully customisable and modern camera implementation for iOS made with AVFoundation.

Features Extremely simple and easy to use Controls autofocus & exposure Customizable interface Code-made UI assets that do not lose resolution quality

Gabriel Alvarado 1.3k Nov 30, 2022
iOS camera engine with Vine-like tap to record, animatable filters, slow motion, segments editing

SCRecorder A Vine/Instagram like audio/video recorder and filter framework in Objective-C. In short, here is a short list of the cool things you can d

Simon Corsin 3.1k Dec 25, 2022
Fasttt and easy camera framework for iOS with customizable filters

FastttCamera is a wrapper around AVFoundation that allows you to build your own powerful custom camera app without all the headaches of using AVFounda

IFTTT 1.8k Dec 10, 2022
Mock UIImagePickerController for testing camera based UI in simulator

Mock UIImagePickerController to simulate the camera in iOS simulator.

Yonat Sharon 18 Aug 18, 2022