A Snapchat Inspired iOS Camera Framework written in Swift

Overview

Platform: iOS 8+ Language: Swift 4.2 CocoaPods compatible License: BSD

Overview

SwiftyCam is a a simple, Snapchat-style iOS Camera framework for easy photo and video capture. SwiftyCam allows users to capture both photos and videos from the same session with very little configuration.

Configuring a Camera View Controller in AVFoundation can be tedious and time consuming. SwiftyCam is a drop in View Controller which gives complete control of the AVSession.

For Swift 4 support, see Swift4 branch

Features

SwiftyCam
😎 Snapchat-style media capture
πŸ‘ Support iOS8+
πŸ“· Image capture
πŸŽ₯ Video capture
πŸ“ˆ Manual image quality settings
πŸŽ‰ Front and rear camera support
πŸ”¦ Front and rear flash
β˜€οΈ Retina flash support
πŸ”Ž Supports manual zoom
πŸ”’ Supports manual focus
🌜 Low light setting
πŸ”ˆ Background audio support

Requirements

  • iOS 8.0+
  • Swift 4.2+

License

SwiftyCam is available under the BSD license. See the LICENSE file for more info.

Installation

Cocoapods:

SwiftyCam is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SwiftyCam"

Carthage

Add this to Cartfile

github "Awalz/SwiftyCam" ~> 2.2.1
$ carthage update SwiftyCam

Manual Installation:

Simply copy the contents of the Source folder into your project.

Usage

Using SwiftyCam is very simple.

Prerequisites:

As of iOS 10, Apple requires the additon of the NSCameraUsageDescription and NSMicrophoneUsageDescription strings to the info.plist of your application. Example:

<key>NSCameraUsageDescription</key>
	<string>To Take Photos and Video</string>
<key>NSMicrophoneUsageDescription</key>
	<string>To Record Audio With Video</string>

Getting Started:

If you install SwiftyCam from Cocoapods, be sure to import the module into your View Controller:

import SwiftyCam

SwiftyCam is a drop-in convenience framework. To create a Camera instance, create a new UIViewController subclass. Replace the UIViewController subclass declaration with SwiftyCamViewController:

class MyCameraViewController : SwiftyCamViewController

That is all that is required to setup the AVSession for photo and video capture. SwiftyCam will prompt the user for permission to use the camera/microphone, and configure both the device inputs and outputs.

Capture

SwiftyCamButton:

SwiftyCam comes with a very convenient method of capturing media. SwiftyCamButton captures photos with a UITapGestureRecognizer and captures video with a UILongPressGestureRecognizer

To use a SwiftyCamButton, simply create one and assign the delegate to your SwiftyCamViewController:

let captureButton = SwiftyCamButton(frame: buttonFrame)
captureButton.delegate = self

Manual:

Capturing media with SwiftyCam is very simple. To capture a photo, simply call the takePhoto function:

takePhoto()

Capturing Video is just as easy. To begin recording video, call the startVideoRecording function:

startVideoRecording()

To end the capture of a video, call the stopVideoRecording function:

stopVideoRecording()

Delegate

In order to acquire the photos and videos taken by either the SwiftyCamButton or manually, you must implement the SwiftyCamViewControllerDelegate and set the cameraDelegate to your view controller instance:

class MyCameraViewController : SwiftyCamViewController, SwiftyCamViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        cameraDelegate = self
    }
    ...
}

Delegate methods:

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didTake photo: UIImage) {
     // Called when takePhoto() is called or if a SwiftyCamButton initiates a tap gesture
     // Returns a UIImage captured from the current session
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didBeginRecordingVideo camera: SwiftyCamViewController.CameraSelection) {
     // Called when startVideoRecording() is called
     // Called if a SwiftyCamButton begins a long press gesture
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishRecordingVideo camera: SwiftyCamViewController.CameraSelection) {
     // Called when stopVideoRecording() is called
     // Called if a SwiftyCamButton ends a long press gesture
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishProcessVideoAt url: URL) {
     // Called when stopVideoRecording() is called and the video is finished processing
     // Returns a URL in the temporary directory where video is stored
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) {
     // Called when a user initiates a tap gesture on the preview layer
     // Will only be called if tapToFocus = true
     // Returns a CGPoint of the tap location on the preview layer
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didChangeZoomLevel zoom: CGFloat) {
	  // Called when a user initiates a pinch gesture on the preview layer
	  // Will only be called if pinchToZoomn = true
	  // Returns a CGFloat of the current zoom level
}

func swiftyCam(_ swiftyCam: SwiftyCamViewController, didSwitchCameras camera: SwiftyCamViewController.CameraSelection) {
     // Called when user switches between cameras
     // Returns current camera selection   
}

Flash

The flash(torch) can be enabled by changing the flashEnabled property:

flashEnabled = true

Flash is now supported for front and rear facing cameras.

Rear Camera

For photos, the camera will flash much like the stock iOS camera. For video, the torch(flash) will enable for the duration of the video capture.

Front Camera

For models that support Retina Flash, the front camera will use the default flash for image capture. If Retina Flash is not supported, a faux Retina Flash is used similar to Snapchat.

For front facing videos, a white, 85% opaque view will be placed over the video feed for the duration of the video capture.

Switching Camera

By default, SwiftyCam will launch to the rear facing camera. This can be changed by changing the defaultCamera property in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    defaultCamera = .front
    ...
}

SwiftyCam supports capture from both the front and back cameras. To switch cameras, call the function:

switchCamera()

Tap-to-focus, pinch-to-zoom and camera flash are not supported when the front facing camera is selected. Switching video while video is being recorded is not currently supported

SwiftyCam also enables switching between cameras with a double tap gesture. To disable this feature, use the doubleTapCameraSwitch property:

doubleTapCameraSwitch = false

Configuration

SwiftyCam has several options for configurating the functionality of the capture:

Video Quality

Video quality can be set by the videoQuality property of SwiftyCamViewController. The choices available correspond to the matching AVCaptureSessionPreset:

VideoQuality AVCaptureSessionPreset
.high AVCapturePresetHigh
.medium AVCapturePresetMedium
.low AVCapturePresetLow
.resolution352x288 AVCaptureSessionPreset352x288
.resolution640x480 AVCaptureSessionPreset640x480
.resolution1280x720 AVCaptureSessionPreset1280x720
.resolution1920x1080 AVCaptureSessionPreset1920x1080
.resolution3840x2160 AVCaptureSessionPreset3840x2160
.iframe960x540 AVCaptureSessionPresetiFrame960x540
.iframe1280x720 AVCaptureSessionPresetiFrame1280x720

The default value is .high. For use with the front-facing camera, .high will always be used.

Maximum Video Duration

If using a SwiftyCamButton, you can set a maximum video duration for the length of video. The video recording will me automatically stopped once the time limit has been reached and the delegate method SwiftyCamDidFinishRecordingVideo will be called. To set this value, simply change the maximumVideoDuration value:

maximumVideoDuration = 10.0

A value of 0.0 will allow for unlimited video recording via the SwiftyCamButton. The default value is 0.0.

Camera Zoom

SwiftyCam supports digital zoom of the camera session via pinch and pan gestures. The gestures work similar to the default iOS app and will zoom to the maximum supported zoom level. Camera zoom is only supported on the rear facing camera. AVFoundation does not currently support front facing camera zoom. To disable this feature, change the pinchToZoom property:

pinchToZoom = false

By default, pinchToZoom is enabled.

SwiftyCam also supports the ability to zoom the rear facing camera with vertical pan gestures. To disable this feature, change the swipeToZoom property:

swipeToZoom = false

By default, swipeToZoom is enabled. The default gestures zoom in the capture session with a downward swipe, and zoom out with an upward swipe. This can be reversed by changing the swipeToZoomInverted property:

swipeToZoomInverted = true

You can also restrict the amount that the rear facing camera can zoom. To do this, use the maxZoomScale property:

maxZoomScale = 2.0

By default, maxZoomScale is set to infinite. The actual maximum zoom level is determined by the device's videoMaxZoomFactor.

Camera Focus

SwiftyCam, by default, support tap to focus on the video preview. SwiftyCam will set the focus and exposure levels of the session to the tapped point. While tap to set exposure is supported on both cameras, tap to focus is only supported on rear facing cameras. Autofocus and autoexposure will be resumed once SwiftyCam detects significant movement from the tapped point. To disable this feature, change the tapToFocus property:

tapToFocus = false

By default, tapToFocus is enabled. If you wish to show a on screen animation when a tap to focus is initiated, you can use the SwiftyCamDidFocusAtPoint(focusPoint:) to get the coordinates of tap and provide your own tap animation

Device Orientation

By default, SwiftyCam will set the photo orientation to be portrait. If you wish to preserve the orientation of the capture photos to allow support for landscape images, use the shouldUseDeviceOrientation property:

shouldUseDeviceOrientation = true

Background Audio

SwiftyCam has the ability to allow background audio to continue playing within the session, and to be captured by the video recording. By default, this is enabled. If you wish to disable this feature, change the allowBackgroundAudio property:

allowBackgroundAudio = false

Low Light Boost

For supported models (iPhone 5 and 5C), AVCaptureDevice supports a low light boost when it is detected that the capture session is in a low light area. By default, this is set to true. It can be modified with the lowLightBoost variable:

lowLightBoost = false

Privacy

When a user firsts launch SwiftyCamViewController, they will be prompted for permission for access to the cameras and microphones. By default, if a user declines access to the hardware, SwiftyCam will provide a prompt to the App privacy settings inside the iOS settings application.

Miscellaneous

Other properties:

  • isCameraFlashOn - Boolean
  • isVideoRecording - Boolean
  • isSessionRunning - Boolean
  • currentCamera - CameraSelection

Contact

If you have any questions, requests, or enhancements, feel free to submit a pull request, create an issue, or contact me in person:

Andrew Walz [email protected]

Comments
  • Having trouble switching cameras

    Having trouble switching cameras

    I cant seem to get the cameras to switch properly. When i switch the camera, i just get a black screen and everything becomes unresponsive. Any way to fix this?

    opened by ryandailey100 18
  • PreviewLayer view sometimes doesnt Fill Screen

    PreviewLayer view sometimes doesnt Fill Screen

    @Awalz This happens randomly, but when I load the CameraViewController, from time to time, the previewLayer frame doesnt not extend to the bounds of my screen.

    I havent done any modification to the library, simply subclassed SwiftyCamViewController with these settings in viewDidLoad

    Update** I dont know if this could perhaps be the problem previewLayer = PreviewView(frame: self.view.frame). I once read somewhere that you should always use view.bounds not frame but I have yet to test.

    // In viewDidLoad
    func cameraSettings() {
            cameraDelegate = self
            defaultCamera = .front
            videoQuality = .medium
            pinchToZoom = false
            flashEnabled = false
            doubleTapCameraSwitch = false
        }
    

    img_4528 img_4527

    opened by otymartin 16
  • Use of CoreMotion instead of UIDevice to detect orientation

    Use of CoreMotion instead of UIDevice to detect orientation

    This improves on the previous orientation detection that was implemented using UIDevice, that will only triggered as long as users haven't locked their screen. CoreMotion will always send these updates regardless if the user have locked the screen or not, which would be the desired behavior for most cases. I haven't done to much performance benchmarking but I believe the frequency of CoreMotion updates checks should be ok.

    opened by jonandersen 8
  • Unable to capture media

    Unable to capture media

    When push camera viewcontroller, I could see the following message.

    Domain=AVFoundationErrorDomain Code=-11814 "Cannot Record" UserInfo={NSLocalizedRecoverySuggestion=Try recording again., NSLocalizedDescription=Cannot Record}

    What should I fix?

    opened by david-koch-pro 7
  • (SOLVED) [SwiftyCam]: Cannot take photo. Capture session is not running

    (SOLVED) [SwiftyCam]: Cannot take photo. Capture session is not running

    [SWIFT 4.2] I've set all the delegates and methods,

    but when I press the button to take photo, it says "[SwiftyCam]: Cannot take photo. Capture session is not running" in the log console.

    Does anyone know the solution?

    opened by andrevinic 6
  • Buttons go out of view frame in landscape mode

    Buttons go out of view frame in landscape mode

    The Camera button, flip camera view button and the flash button is not visible in landscape mode (at least in the demo project).

    Same behavior in Xcode simulator as well as physical device (iPhone).

    swiftycam

    opened by annjawn 6
  • Using Storyboards?

    Using Storyboards?

    While I love this component and how simple it is, I'm having quite a weird situation... I've got everything working as per the demo example, but there is a thing that keeps me bothering, and it's creating the buttons in runtime with fixed frames. Since I hate working with constraints in code I decided to build a simple XIB and setup the buttons there. The problem is that the previewView hides the buttons! From what I understand, the previewView is added later on, so it covers everything that's there; so adding the buttons after view did load manages to put the buttons above. For now I'm gonna try moving the buttons to front, but is there any other way?

    opened by andres-cianio 5
  • videoPreviewLayer - Main Thread Checker - Video Not Recording

    videoPreviewLayer - Main Thread Checker - Video Not Recording

    I've so far attempted wrapping every instance of 'videoPreviewLayer' in the function DispatchQueue.main.async or sync throughout my code and as well unlocking and modifying the swiftycam pod files the same to solve the problem but haven't had any success.

    The instantiation of a SwiftyViewController is wrapped within a DispatchQueue.main.async {}.

    If I turn off UIMainThreadChecker the only thing that occurs is my captureButton grows then ungrows, and the method didFinishRecordingTo gets called. But no video is captured.

    Any guidance toward a possible solution would be amazing, Thanks!

    opened by ElliottDiaz 4
  • panGesture is not optional

    panGesture is not optional

    Hello,

    PanGesture can interfere with other Scroll recognizer that uses swipe gesture in the same view controller. It is not possible to remove panGesture (swipe to zoom) from being registered into previewLayer recognizer without altering the source code. This happen due to panGesture is set as private function and no option to remove it from code.

    It should allow the following code to run optionally :

            if PanGestureEnabled == true {
                panGesture = UIPanGestureRecognizer(target: self, 
                                                            action: #selector(panGesture(pan:)))
                panGesture.delegate = self
                previewLayer.addGestureRecognizer(panGesture)
            }
    
    opened by thebigkhaled 4
  • Custom buttons in view ignore storyboard layouts

    Custom buttons in view ignore storyboard layouts

    After I upgraded to 2.4 I ran into an issue with a couple of custom items I was adding to my layout. My outlets were returning nil, so I figured they were not being added to my main vew so I manually added them but in version 2.3 I was able to do this in the storyboard and I was able to assign constraints etc to lay them out. Now I can't. What am I missing? See screenshots attached.

    override func viewDidLoad() {
        super.viewDidLoad()
       
        cameraDelegate = self
        
        addButtons()
        
        // In version 2.4
        view.addSubview(eventField)
        view.addSubview(eventLabel)
        view.addSubview(backButton)
        view.addSubview(addButton)
    
        // In version 2.3
    

    // view.bringSubview(toFront: eventField) // view.bringSubview(toFront: eventLabel) // view.bringSubview(toFront: backButton) // view.bringSubview(toFront: addButton) }

    screen shot 2017-06-26 at 9 43 12 pm simulator screen shot jun 26 2017 9 54 00 pm

    opened by caesss 4
  • Button not appearing in view

    Button not appearing in view

    I have the code below, however button is not showing up in view. Is there something I am missing?

    import UIKit
    import SwiftyCam
    
    class CameraViewController: SwiftyCamViewController, SwiftyCamViewControllerDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tabBarController?.tabBar.isHidden = true
            
            let buttonFrame = CGRect(x: 200, y:600, width:200, height:200)
    
            let captureButton = SwiftyCamButton(frame: buttonFrame)
            
            cameraDelegate = self
            
            captureButton.delegate = self
            
            view.addSubview(captureButton)
            
        }
    

    @Awalz

    opened by alexcowley 4
  • Is there a fork of this library that is most up to date?

    Is there a fork of this library that is most up to date?

    This library is a bit old and there are a lot of deprecated classes like AVCaptureStillImageOutput, and AVCaptureDevice.devices(). Is there a fork somewhere that someone is maintaining and keeping up to date that solves those issues?

    opened by waterdrake 0
  • Camera looks

    Camera looks "zoomed in" compared to other full screen apps when using videoGravity: .resizeAspectFill

    I have the camera set to full screen using videoGravity: .resizeAspectFill

    However, now the camera looks "zoomed in" compared to other apps that are full screen cameras.

    Any thoughts on how to fix this?

    Below are links to 2 images to compare:

    SwiftyCam

    OtherCam

    opened by lifecloudsocial 0
Releases(4.0.0)
Owner
Andrew Walz
Mobile Developer
Andrew Walz
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
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
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
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
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
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
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
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
Video and photo camera for iOS

Features: Description Records video ?? takes photos ?? Flash on/off ⚑ Front / Back camera ↕️ Hold to record video ✊ Tap to take photo ?? Tap to focus

AndrΓ© J 192 Dec 17, 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
Simple Swift class to provide all the configurations you need to create custom camera view in your app

Camera Manager This is a simple Swift class to provide all the configurations you need to create custom camera view in your app. It follows orientatio

Imaginary Cloud 1.3k Dec 29, 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
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
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
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
Mock UIImagePickerController for testing camera based UI in simulator

Mock UIImagePickerController to simulate the camera in iOS simulator.

Yonat Sharon 18 Aug 18, 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