Code Monkey home page Code Monkey logo

cameramanager's Introduction

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.

cameramanager's People

Contributors

andreamazz avatar aukaost avatar brightsider avatar davidortinau avatar davidy avatar dimohamdy avatar dpereira411 avatar elikohen avatar gamafranco avatar gbmksquare avatar iamtomcat avatar igorkulman avatar jakubmazur avatar jasonlagaac avatar joelfsreis avatar lexrus avatar lucasmpaim avatar mabuak avatar miguelcampiao avatar nelanelanela avatar phlippieb avatar rivera-ernesto avatar rubyboy avatar sbfcant avatar songjiaqiang avatar timothyqiu avatar torrao avatar xc0der avatar yurkins avatar zaubara avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cameramanager's Issues

Dark PreviewLayerView

When I switching from .StillImage to .VideoWithMic and vice versa the PreviewLayerView becomes dark for a few seconds

When you stop and resume capture session, orientation detection doesn't work anymore

I have modified the demo project in order to add the possibility to switch to another screen and then come back. This way, viewWillDisappear is called on ViewController, and then viewWillAppear is called again, resulting in stopCaptureSession being called and then resumeCaptureSession. In that case, when you try to switch from portrait to landcape, the preview is all skewed.

Just making some changes.

Hey not really an issue, but wanted to let you know I've been slowly working on a fork that you may want to eventually pull back into your project. It's not done on my end, but I keep pulling in your changes as they happen so it's pretty up to date with what you've done.

I've already got zoom working on my end. Also I've gotten rid of the Assets library and switched to the photos framework.

Readme bug

Your Podfile import statement has a smart quote at the end, should be:

pod 'CameraManager', '~> 2.2'

When flash is on, app is crashing in capturePictureWithCompletion

This is error I am seeing, domain: "AVFoundationErrorDomain" - code: 11800.

It was working before, even currently works without the flash functionality. Not sure as to what happened.

Just fixed the issue, its not specific to CameraManager, but heads up for people using a segue on taking a picture, it will work without flash but will break if flash is on. Need to make the capture button link to the action instead of prepareForSegue.

video orientation not set after camera switch

After I switch the camera (front to back or back to front) while .shouldRespondToOrientationChanges is set to true, and begin recording in a landscape orientation (either right or left), the output video will be rotated incorrectly.

My current "fix" is to just call _orientationChanged() inside the cameraDevice didSet block. This probably isn't a universal fix, though, since not everyone will want the camera to respond to orientation changes. I can investigate a more complete fix and submit a PR if you'd like. Let me know.

Mistypos in method names, some in ReadME

in readme

  • under 'how to use': ... or the user denied assess to it.

in code base

  • capturePictureWithCompletition and a couple more like them have mispelled wordings. Should be 'Completion"

I would double check others as well!

Missing project's short description

the description could be something like "CameraManager - Simple Swift class to provide all the configurations you need to create custom camera view in your app.

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

Carthage installation no longer working with Xcode 8

Recently updated to Xcode 8 since the general release was today and I get errors overtime I try and build with carthage. I get the following errors:

-scheme CameraManager -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** CLEAN FAILED **

Any suggestions?

Thanks in advance!

error on fast switch of cameras

Cannot add output <AVCaptureMovieFileOutput: 0x1577f0f0> to capture session <AVCaptureSession: 0x168e2a20 [AVCaptureSessionPresetPhoto]> <AVCaptureDeviceInput: 0x157e9480 [Back Camera]> -> <AVCaptureVideoPreviewLayer: 0x157dfd10> <AVCaptureDeviceInput: 0x157e9480 [Back Camera]> -> <AVCaptureStillImageOutput: 0x157f2360> because more than one output of the same type is unsupported.

This is the error i got, and this is the line

  private func _getMovieOutput() -> AVCaptureMovieFileOutput {
        var shouldReinitializeMovieOutput = movieOutput == nil
        if !shouldReinitializeMovieOutput {
            if let connection = movieOutput!.connectionWithMediaType(AVMediaTypeVideo) {
                shouldReinitializeMovieOutput = shouldReinitializeMovieOutput || !connection.active
            }
        }

        if shouldReinitializeMovieOutput {
            movieOutput = AVCaptureMovieFileOutput()
            movieOutput!.movieFragmentInterval = kCMTimeInvalid

            captureSession?.beginConfiguration()

//this line is where the code exploted
            captureSession?.addOutput(movieOutput)
            captureSession?.commitConfiguration()
        }
        return movieOutput!
    }

Saving of video will silently fail occasionally

Hello,
We've had several reports from users using our app WeTime (which is using CameraManager), that in very rare occasions, the saving of their recording video would fail.
We've been trying to trace the exact location of the failure using remote logging tools and believe we have narrowed it down to the stopRecordingVideo method.

Our code looks like this:

Mobihelp.sharedInstance().leaveBreadcrumb("About to call cameraManager.stopRecordingVideo")
cameraManager.stopRecordingVideo(self.saveVideo)

...


private func saveVideo(tempVideoURL: NSURL?, error: NSError?) -> Void {
    Mobihelp.sharedInstance().leaveBreadcrumb("saveVideo called")
   ...

We see the first breadcrumb correctly being set, but in the cases where people lost their recorded video, saveVideo doesn't seem to ever have been actually called.

Looking at the stopRecordingVideo method, it seems that a lot could actually go wrong without us knowing about it (movieOutput could be nil, or it could not be recording).

What are your thoughts on getting some better handling of these edge cases (maybe using _show to display the error)?

xcode 8

can you make new branch for swift2.3 and swift3?

Problem with addPreviewLayerToView on iPad

I am trying to use this library on an iPad. On iPhone iOS 9.1 it is working 100% however on the iPad the addPreviewLayerToView callback of completion never gets called.

        cameraManager.addPreviewLayerToView(self.imageView, newCameraOutputMode: .VideoWithMic, completition: {
            print("Camera ready")
            self.cameraCounter = 5
            self.timer = Interval.repeating(1, closure: self.prepareTick)
        })

For 2.0

'stringByAppendingPathExtension' is unavailable: Use URLByAppendingPathExtension on NSURL instead.

More than one output of the same type is unsupported.

Sometimes, The Demo crashed and printed below log:

2016-04-22 17:42:48.136 camera[902:654638] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* Cannot add output <AVCaptureMovieFileOutput: 0x127e659a0> to capture session <AVCaptureSession: 0x127d44400 [AVCaptureSessionPresetPhoto]>
<AVCaptureDeviceInput: 0x127e42fa0 [Back Camera]> -> <AVCaptureVideoPreviewLayer: 0x127e70d20>
<AVCaptureDeviceInput: 0x127e42fa0 [Back Camera]> -> <AVCaptureMovieFileOutput: 0x127e72080>
<AVCaptureDeviceInput: 0x127dd8340 [iPhone 麦克风]> -> <AVCaptureMovieFileOutput: 0x127e72080> because more than one output of the same type is unsupported.'
*** First throw call stack:
(0x18401ee38 0x183683f80 0x18a75cbd8 0x18a75c93c 0x1000f1b84 0x1000f23ec 0x1000f41c8 0x1000ed9d0 0x1000eda3c 0x1000fa2a4 0x1000fc72c 0x1000fa960 0x100795a7c 0x100795a3c 0x1007a2554 0x10079972c 0x100795a3c 0x1007a4c9c 0x1007a4364 0x183c81470 0x183c81020)
libc++abi.dylib: terminating with uncaught exception of type NSException

Recorded video has no sound

It only happens when the video is longer than around 10 seconds. Easy to reproduce in sample project. That asset's tracksWithMediaType(AVMediaTypeAudio) is empty 😢

Feature request: Add option of what album to write image to

Hey, thanks for writing such a nice manager.

When setting writeFilesToPhoneLibrary it will write the file to the library, but it'd be nice to have the option of setting what album to write it to.

Alternatively, a hook for the completionblock of writeImageDataToSavedPhotosAlbum would make it equally simple? Then again, writeImageDataToSavedPhotosAlbum is deprecated in iOS 9, so I'm a bit confused as to what direction would be preferable. :-)

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.'

Insert previewLayer to subLayer of cameraView (Feature Request)

@nelanelanela @torrao

Hey would really like to be able to add the preview layer to the cameraView sublayer that way its easier to add content on top of my cameraView. Specifically, I want to add a blur to my camera view along with buttons, labels and icons but the preview layer takes precedence.

I just switched from CameraEngine where what I'm trying to do worked perfectly.

let layer = self.cameraEngine.previewLayer
        layer.frame = self.cameraView.bounds
        self.cameraView.layer.insertSublayer(layer, atIndex: 0)

//I could then add a blur effect on top of it like so
    //BLUR EFFECT
        let blurEffect = UIBlurEffect(style: .Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.cameraView.bounds
        blurEffectView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.7)
        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        self.cameraView.addSubview(blurEffectView)

Preview Layer is always on top

I would like to be able to have views on top of the preview layer, i.e. have buttons added to the container view AFTER CameraManager.sharedInstance.addPreviewLayerToView(self.view) is called and have those views appear on top of the preview layer.

Quick Question

Hello, So I set up an alarm with camera manager. Is it possible to send over an array of these images to image view?

Crash when trying to capture a still image

When I run the following code:

CameraManager.sharedInstance.capturePictureWithCompletition({ (image) -> Void in
            self.imageView.hidden = false
            self.imageView.image = image
})

I get the following exception:

2014-12-02 21:27:39.343 Pixync[8928:3126855] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[AVCaptureStillImageOutput captureStillImageAsynchronouslyFromConnection:completionHandler:] - inactive/invalid connection passed.'
*** First throw call stack:
(0x187c7e59c 0x1983d00e4 0x186515140 0x100100360 0x1000ed4b8 0x1008b8e30 0x1008b8df0 0x1008c3854 0x1008bc120 0x1008c575c 0x1008c6f18 0x198bf12e4 0x198bf0fa8)
libc++abi.dylib: terminating with uncaught exception of type NSException

Zoom

Need to update to add zoom. Mentioned before. This is a key aspect of a camera.

How to properly deal with interruptions

What is the proper way to stop recording and save the video when the recording gets interrupted (eg. by a phone call)?
I've been trying to do this properly but can't seem to get the video to save, and I end up losing whatever recording I had made.

Missing image metadata

When image is captured closure doesn't pass back image metadata dictionary (exif, etc)

error when trying to record video

Hi,

I am trying to setup video recording. I have the following code:

    let cameraManager = CameraManager()

    cameraManager.cameraDevice = .Back
    cameraManager.cameraOutputMode = .VideoWithMic
    cameraManager.cameraOutputQuality = .High
    cameraManager.writeFilesToPhoneLibrary = true

    cameraManager.addPreviewLayerToView(self.imageView)


    cameraManager.startRecordingVideo()

I get the following error when startRecordingVideo is called:

2015-12-23 22:52:25.643 RocketBash[1503:819683] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[AVCaptureMovieFileOutput startRecordingToOutputFileURL:recordingDelegate:] - no active/enabled connections.'

Anything else I need to do? or something I have done in error?

two errors when compile

  1. 'stringByAppendingPathComponent' has been explicitly marked unavailable here
  2. 'stringByAppendingPathExtension' has been explicitly marked unavailable here
    2015-09-17 11 07 47

Orientation Issue

When you go to a new view controller from the camera and then rotate orientation and then dismiss the current view controller the UIView is not rotated and is cut off. This is also in the example project that is in the repository

Outputting Video

Hello, thanks so much for your cocoapod. How can I get the video content once it's taken. I notice that video automatically gets saved to the user's phone but I'd like my user to have the ability to edit the footage before it saves to their phone

Unresolved identifier

When I integrate CameraManager in my project via CocoaPods, it doesn't see the CameraManager class. The compiler says "Use of unresolved identifier 'CameraManager'. Is there anything special I should do to expose CameraManager class to my Swift classes? Obviously I don't have to add a #import to my bridging header, but I'm wondering if there's an equivalent. Note that I'm using CocoaPods 0.35 (the latest version to date).

Setting Camera as initial device

Hello, for starters thank you tremendously for this launching point it's so hard to find any references or help in understand the camera functionality for ios 8. My question is really quick, I noticed that in the actual view controller for where the camera will be shown it's possible to set which device opens first.

In your code you have self.cameraManager.cameraOutputMode = .StillImage and for instance if I were to write self.cameraManager.cameraDevice = .Front the front camera would launch as soon as the camera session starts instead of the back. My question is this i have self.cameraManager.cameraOutputMode = .StillImage set but no matter what I try the video camera opens up initially anyways. Is their a way to override this in your cameraManager class?

Horizontally mirror camera

There should be a variable, mirrorOutput that flips the output and the preview layer along the y axis.

Something like:

var mirrorOutput = false {
    willSet {
         switch self.cameraOutputModel {
             case .VideoWithMic, VideoOnly:
                 if let connections = self.movieOutput?.connections {
                     for connection in connections {
                         for port in connection.inputPort {
                             if let videoConnection = connection as? AVCaptureConnection where port.mediaType = AVMediaTypeVideo && videoConnection.supportsVideoMirroring {
                                    videoConnection.videoMirrored = true
                             }
                         }
                 }
         }
    }
}

That's the general gist of it.

zoom not working???

Hi, im running camera manager on XCode 7.2 using Swift 2.0 and am having an issue with zoom. I downloaded your example and everything seems to be working just fine, but when I add it to a blank project using Carthage, it wont zoom. I added a sub view to my view, created an outlet and the camera image shows up but when I pinch to zoom nothing happens. I'm wondering if I have to add some sort of setting to the cameraView or set some flag for zoom to work? Sorry if it's something obvious, im just not seeing it.

Thank you.

CameraManager detects flash on front camera, but it shouldn't

I found a weird behavior, when I use the front camera of my iPhone 5s. The front camera doesn't support flash. But if I call
cameraManager.hasFlash
it returns "true" anyway. Why is that?

If I try to make a video now, the app starts recording accordingly with the front camera.. but at the start of the recording the flash of the back camera turns on for a second for no reason at all.

Same behavior with the example app.

Anyway thank you a lot for this great library!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.