How to switch camera using AVFoundation












0















I have implemented the preview camera using AVFoundation, its working fine. But I have a hard time to switch the camera back and front. I have added a switch button at the bottom bar. By default, its the back camera, I want to switch it to front. How can I do that?



class FifteenSecsViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

@IBOutlet weak var camPreview: UIView!
let captureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var previewLayer: AVCaptureVideoPreviewLayer!
var activeInput: AVCaptureDeviceInput!
var outputURL: URL!

override func viewDidLoad() {
super.viewDidLoad()

if setupSession() {
setupPreview()
startSession()
}
self.switchCameraButton.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
}

func setupSession() -> Bool {

captureSession.sessionPreset = AVCaptureSession.Preset.high

// Setup Camera
let camera: AVCaptureDevice?

camera = AVCaptureDevice.default(for: .video)
do {
let input = try AVCaptureDeviceInput(device: camera!)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
activeInput = input
}
} catch {
print("Error setting device video input: (error)")
return false
}

// Setup Microphone
let microphone = AVCaptureDevice.default(for: .audio)

do {
let micInput = try AVCaptureDeviceInput(device: microphone!)
if captureSession.canAddInput(micInput) {
captureSession.addInput(micInput)
}
} catch {
print("Error setting device audio input: (error)")
return false
}


// Movie output
let seconds : Int64 = 3
let maxDuration = CMTime(seconds: Double(seconds),
preferredTimescale: 1)
movieOutput.maxRecordedDuration = maxDuration
if captureSession.canAddOutput(movieOutput) {
captureSession.addOutput(movieOutput)
}

return true
}

func setupPreview() {
// Configure previewLayer
previewLayer = AVCaptureVideoPreviewLayer(session:
captureSession)
previewLayer.frame = camPreview.bounds
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
camPreview.layer.addSublayer(previewLayer)
}

//MARK:- Camera Session
func startSession() {
if !captureSession.isRunning {
videoQueue().async {
self.captureSession.startRunning()
}
}
}

@objc func switchButtonTapped(){
// what to write here??
}

}


Function switchButtonTapped is an actionTarget of UIButton. If I add this code in this button:



@objc func switchButtonTapped(){

if setupSession() {
setupPreview()
startSession()
}
}


Camerapreview screen shows a white screen and got stuck.










share|improve this question

























  • checkout this link may be it helps you stackoverflow.com/questions/20864372/…

    – jignesh Vadadoriya
    Jan 1 at 11:56











  • Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

    – Magnas
    Jan 1 at 11:58
















0















I have implemented the preview camera using AVFoundation, its working fine. But I have a hard time to switch the camera back and front. I have added a switch button at the bottom bar. By default, its the back camera, I want to switch it to front. How can I do that?



class FifteenSecsViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

@IBOutlet weak var camPreview: UIView!
let captureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var previewLayer: AVCaptureVideoPreviewLayer!
var activeInput: AVCaptureDeviceInput!
var outputURL: URL!

override func viewDidLoad() {
super.viewDidLoad()

if setupSession() {
setupPreview()
startSession()
}
self.switchCameraButton.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
}

func setupSession() -> Bool {

captureSession.sessionPreset = AVCaptureSession.Preset.high

// Setup Camera
let camera: AVCaptureDevice?

camera = AVCaptureDevice.default(for: .video)
do {
let input = try AVCaptureDeviceInput(device: camera!)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
activeInput = input
}
} catch {
print("Error setting device video input: (error)")
return false
}

// Setup Microphone
let microphone = AVCaptureDevice.default(for: .audio)

do {
let micInput = try AVCaptureDeviceInput(device: microphone!)
if captureSession.canAddInput(micInput) {
captureSession.addInput(micInput)
}
} catch {
print("Error setting device audio input: (error)")
return false
}


// Movie output
let seconds : Int64 = 3
let maxDuration = CMTime(seconds: Double(seconds),
preferredTimescale: 1)
movieOutput.maxRecordedDuration = maxDuration
if captureSession.canAddOutput(movieOutput) {
captureSession.addOutput(movieOutput)
}

return true
}

func setupPreview() {
// Configure previewLayer
previewLayer = AVCaptureVideoPreviewLayer(session:
captureSession)
previewLayer.frame = camPreview.bounds
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
camPreview.layer.addSublayer(previewLayer)
}

//MARK:- Camera Session
func startSession() {
if !captureSession.isRunning {
videoQueue().async {
self.captureSession.startRunning()
}
}
}

@objc func switchButtonTapped(){
// what to write here??
}

}


Function switchButtonTapped is an actionTarget of UIButton. If I add this code in this button:



@objc func switchButtonTapped(){

if setupSession() {
setupPreview()
startSession()
}
}


Camerapreview screen shows a white screen and got stuck.










share|improve this question

























  • checkout this link may be it helps you stackoverflow.com/questions/20864372/…

    – jignesh Vadadoriya
    Jan 1 at 11:56











  • Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

    – Magnas
    Jan 1 at 11:58














0












0








0








I have implemented the preview camera using AVFoundation, its working fine. But I have a hard time to switch the camera back and front. I have added a switch button at the bottom bar. By default, its the back camera, I want to switch it to front. How can I do that?



class FifteenSecsViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

@IBOutlet weak var camPreview: UIView!
let captureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var previewLayer: AVCaptureVideoPreviewLayer!
var activeInput: AVCaptureDeviceInput!
var outputURL: URL!

override func viewDidLoad() {
super.viewDidLoad()

if setupSession() {
setupPreview()
startSession()
}
self.switchCameraButton.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
}

func setupSession() -> Bool {

captureSession.sessionPreset = AVCaptureSession.Preset.high

// Setup Camera
let camera: AVCaptureDevice?

camera = AVCaptureDevice.default(for: .video)
do {
let input = try AVCaptureDeviceInput(device: camera!)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
activeInput = input
}
} catch {
print("Error setting device video input: (error)")
return false
}

// Setup Microphone
let microphone = AVCaptureDevice.default(for: .audio)

do {
let micInput = try AVCaptureDeviceInput(device: microphone!)
if captureSession.canAddInput(micInput) {
captureSession.addInput(micInput)
}
} catch {
print("Error setting device audio input: (error)")
return false
}


// Movie output
let seconds : Int64 = 3
let maxDuration = CMTime(seconds: Double(seconds),
preferredTimescale: 1)
movieOutput.maxRecordedDuration = maxDuration
if captureSession.canAddOutput(movieOutput) {
captureSession.addOutput(movieOutput)
}

return true
}

func setupPreview() {
// Configure previewLayer
previewLayer = AVCaptureVideoPreviewLayer(session:
captureSession)
previewLayer.frame = camPreview.bounds
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
camPreview.layer.addSublayer(previewLayer)
}

//MARK:- Camera Session
func startSession() {
if !captureSession.isRunning {
videoQueue().async {
self.captureSession.startRunning()
}
}
}

@objc func switchButtonTapped(){
// what to write here??
}

}


Function switchButtonTapped is an actionTarget of UIButton. If I add this code in this button:



@objc func switchButtonTapped(){

if setupSession() {
setupPreview()
startSession()
}
}


Camerapreview screen shows a white screen and got stuck.










share|improve this question
















I have implemented the preview camera using AVFoundation, its working fine. But I have a hard time to switch the camera back and front. I have added a switch button at the bottom bar. By default, its the back camera, I want to switch it to front. How can I do that?



class FifteenSecsViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {

@IBOutlet weak var camPreview: UIView!
let captureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var previewLayer: AVCaptureVideoPreviewLayer!
var activeInput: AVCaptureDeviceInput!
var outputURL: URL!

override func viewDidLoad() {
super.viewDidLoad()

if setupSession() {
setupPreview()
startSession()
}
self.switchCameraButton.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
}

func setupSession() -> Bool {

captureSession.sessionPreset = AVCaptureSession.Preset.high

// Setup Camera
let camera: AVCaptureDevice?

camera = AVCaptureDevice.default(for: .video)
do {
let input = try AVCaptureDeviceInput(device: camera!)
if captureSession.canAddInput(input) {
captureSession.addInput(input)
activeInput = input
}
} catch {
print("Error setting device video input: (error)")
return false
}

// Setup Microphone
let microphone = AVCaptureDevice.default(for: .audio)

do {
let micInput = try AVCaptureDeviceInput(device: microphone!)
if captureSession.canAddInput(micInput) {
captureSession.addInput(micInput)
}
} catch {
print("Error setting device audio input: (error)")
return false
}


// Movie output
let seconds : Int64 = 3
let maxDuration = CMTime(seconds: Double(seconds),
preferredTimescale: 1)
movieOutput.maxRecordedDuration = maxDuration
if captureSession.canAddOutput(movieOutput) {
captureSession.addOutput(movieOutput)
}

return true
}

func setupPreview() {
// Configure previewLayer
previewLayer = AVCaptureVideoPreviewLayer(session:
captureSession)
previewLayer.frame = camPreview.bounds
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
camPreview.layer.addSublayer(previewLayer)
}

//MARK:- Camera Session
func startSession() {
if !captureSession.isRunning {
videoQueue().async {
self.captureSession.startRunning()
}
}
}

@objc func switchButtonTapped(){
// what to write here??
}

}


Function switchButtonTapped is an actionTarget of UIButton. If I add this code in this button:



@objc func switchButtonTapped(){

if setupSession() {
setupPreview()
startSession()
}
}


Camerapreview screen shows a white screen and got stuck.







ios swift avfoundation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 19:34









Yannick Loriot

6,34622850




6,34622850










asked Jan 1 at 11:32









Muneeb JanMuneeb Jan

154




154













  • checkout this link may be it helps you stackoverflow.com/questions/20864372/…

    – jignesh Vadadoriya
    Jan 1 at 11:56











  • Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

    – Magnas
    Jan 1 at 11:58



















  • checkout this link may be it helps you stackoverflow.com/questions/20864372/…

    – jignesh Vadadoriya
    Jan 1 at 11:56











  • Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

    – Magnas
    Jan 1 at 11:58

















checkout this link may be it helps you stackoverflow.com/questions/20864372/…

– jignesh Vadadoriya
Jan 1 at 11:56





checkout this link may be it helps you stackoverflow.com/questions/20864372/…

– jignesh Vadadoriya
Jan 1 at 11:56













Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

– Magnas
Jan 1 at 11:58





Supplying only a link as an answer is discouraged. The link can break if the page moves. Please consider explaining the basics of the answer you are providing since we’re not here to do basic searches that the OP could do themselves.

– Magnas
Jan 1 at 11:58












2 Answers
2






active

oldest

votes


















0














To begin create a device input for the front camera:



let frontDevice: AVCaptureDevice? = {
for device in AVCaptureDevice.devices(for: AVMediaType.video) {
if device.position == .front {
return device
}
}

return nil
}()

lazy var frontDeviceInput: AVCaptureDeviceInput? = {
if let _frontDevice = self.frontDevice {
return try? AVCaptureDeviceInput(device: _frontDevice)
}

return nil
}()


Then in your switchButtonTapped, if there is a front camera you can do the switch between the front and the ones:



func switchButtonTapped() {
if let _frontDeviceInput = frontDeviceInput {
captureSession.beginConfiguration()

if let _currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
captureSession.removeInput(_currentInput)

let newDeviceInput = (_currentInput.device.position == .front) ? activeInput : _frontDeviceInput
captureSession.addInput(newDeviceInput!)
}

captureSession.commitConfiguration()
}
}


If you need more details, don't hesitate.






share|improve this answer
























  • Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

    – Muneeb Jan
    Jan 2 at 9:32











  • Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

    – Yannick Loriot
    Jan 2 at 15:54



















0














Try this code:



func switchCamera() {
session?.beginConfiguration()
let currentInput = session?.inputs.first as? AVCaptureDeviceInput
session?.removeInput(currentInput!)
let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice!)
session?.addInput(newVideoInput!)
session?.commitConfiguration()
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53995076%2fhow-to-switch-camera-using-avfoundation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    To begin create a device input for the front camera:



    let frontDevice: AVCaptureDevice? = {
    for device in AVCaptureDevice.devices(for: AVMediaType.video) {
    if device.position == .front {
    return device
    }
    }

    return nil
    }()

    lazy var frontDeviceInput: AVCaptureDeviceInput? = {
    if let _frontDevice = self.frontDevice {
    return try? AVCaptureDeviceInput(device: _frontDevice)
    }

    return nil
    }()


    Then in your switchButtonTapped, if there is a front camera you can do the switch between the front and the ones:



    func switchButtonTapped() {
    if let _frontDeviceInput = frontDeviceInput {
    captureSession.beginConfiguration()

    if let _currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
    captureSession.removeInput(_currentInput)

    let newDeviceInput = (_currentInput.device.position == .front) ? activeInput : _frontDeviceInput
    captureSession.addInput(newDeviceInput!)
    }

    captureSession.commitConfiguration()
    }
    }


    If you need more details, don't hesitate.






    share|improve this answer
























    • Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

      – Muneeb Jan
      Jan 2 at 9:32











    • Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

      – Yannick Loriot
      Jan 2 at 15:54
















    0














    To begin create a device input for the front camera:



    let frontDevice: AVCaptureDevice? = {
    for device in AVCaptureDevice.devices(for: AVMediaType.video) {
    if device.position == .front {
    return device
    }
    }

    return nil
    }()

    lazy var frontDeviceInput: AVCaptureDeviceInput? = {
    if let _frontDevice = self.frontDevice {
    return try? AVCaptureDeviceInput(device: _frontDevice)
    }

    return nil
    }()


    Then in your switchButtonTapped, if there is a front camera you can do the switch between the front and the ones:



    func switchButtonTapped() {
    if let _frontDeviceInput = frontDeviceInput {
    captureSession.beginConfiguration()

    if let _currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
    captureSession.removeInput(_currentInput)

    let newDeviceInput = (_currentInput.device.position == .front) ? activeInput : _frontDeviceInput
    captureSession.addInput(newDeviceInput!)
    }

    captureSession.commitConfiguration()
    }
    }


    If you need more details, don't hesitate.






    share|improve this answer
























    • Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

      – Muneeb Jan
      Jan 2 at 9:32











    • Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

      – Yannick Loriot
      Jan 2 at 15:54














    0












    0








    0







    To begin create a device input for the front camera:



    let frontDevice: AVCaptureDevice? = {
    for device in AVCaptureDevice.devices(for: AVMediaType.video) {
    if device.position == .front {
    return device
    }
    }

    return nil
    }()

    lazy var frontDeviceInput: AVCaptureDeviceInput? = {
    if let _frontDevice = self.frontDevice {
    return try? AVCaptureDeviceInput(device: _frontDevice)
    }

    return nil
    }()


    Then in your switchButtonTapped, if there is a front camera you can do the switch between the front and the ones:



    func switchButtonTapped() {
    if let _frontDeviceInput = frontDeviceInput {
    captureSession.beginConfiguration()

    if let _currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
    captureSession.removeInput(_currentInput)

    let newDeviceInput = (_currentInput.device.position == .front) ? activeInput : _frontDeviceInput
    captureSession.addInput(newDeviceInput!)
    }

    captureSession.commitConfiguration()
    }
    }


    If you need more details, don't hesitate.






    share|improve this answer













    To begin create a device input for the front camera:



    let frontDevice: AVCaptureDevice? = {
    for device in AVCaptureDevice.devices(for: AVMediaType.video) {
    if device.position == .front {
    return device
    }
    }

    return nil
    }()

    lazy var frontDeviceInput: AVCaptureDeviceInput? = {
    if let _frontDevice = self.frontDevice {
    return try? AVCaptureDeviceInput(device: _frontDevice)
    }

    return nil
    }()


    Then in your switchButtonTapped, if there is a front camera you can do the switch between the front and the ones:



    func switchButtonTapped() {
    if let _frontDeviceInput = frontDeviceInput {
    captureSession.beginConfiguration()

    if let _currentInput = captureSession.inputs.first as? AVCaptureDeviceInput {
    captureSession.removeInput(_currentInput)

    let newDeviceInput = (_currentInput.device.position == .front) ? activeInput : _frontDeviceInput
    captureSession.addInput(newDeviceInput!)
    }

    captureSession.commitConfiguration()
    }
    }


    If you need more details, don't hesitate.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 1 at 19:32









    Yannick LoriotYannick Loriot

    6,34622850




    6,34622850













    • Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

      – Muneeb Jan
      Jan 2 at 9:32











    • Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

      – Yannick Loriot
      Jan 2 at 15:54



















    • Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

      – Muneeb Jan
      Jan 2 at 9:32











    • Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

      – Yannick Loriot
      Jan 2 at 15:54

















    Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

    – Muneeb Jan
    Jan 2 at 9:32





    Hi, thankyou so much it worked. but when i tapped the switchbutton again, the app crashes with an error ;"An AVCaptureInput instance may not be added to more than one session'"

    – Muneeb Jan
    Jan 2 at 9:32













    Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

    – Yannick Loriot
    Jan 2 at 15:54





    Are you sure you don't add the activeInput elsewhere? You can check whether the activeInput is already present in the captureSession.inputs and add/remove it accordingly.

    – Yannick Loriot
    Jan 2 at 15:54













    0














    Try this code:



    func switchCamera() {
    session?.beginConfiguration()
    let currentInput = session?.inputs.first as? AVCaptureDeviceInput
    session?.removeInput(currentInput!)
    let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
    let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice!)
    session?.addInput(newVideoInput!)
    session?.commitConfiguration()
    }





    share|improve this answer




























      0














      Try this code:



      func switchCamera() {
      session?.beginConfiguration()
      let currentInput = session?.inputs.first as? AVCaptureDeviceInput
      session?.removeInput(currentInput!)
      let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
      let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice!)
      session?.addInput(newVideoInput!)
      session?.commitConfiguration()
      }





      share|improve this answer


























        0












        0








        0







        Try this code:



        func switchCamera() {
        session?.beginConfiguration()
        let currentInput = session?.inputs.first as? AVCaptureDeviceInput
        session?.removeInput(currentInput!)
        let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
        let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice!)
        session?.addInput(newVideoInput!)
        session?.commitConfiguration()
        }





        share|improve this answer













        Try this code:



        func switchCamera() {
        session?.beginConfiguration()
        let currentInput = session?.inputs.first as? AVCaptureDeviceInput
        session?.removeInput(currentInput!)
        let newCameraDevice = currentInput?.device.position == .back ? getCamera(with: .front) : getCamera(with: .back)
        let newVideoInput = try? AVCaptureDeviceInput(device: newCameraDevice!)
        session?.addInput(newVideoInput!)
        session?.commitConfiguration()
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 10:31









        SamSam

        655218




        655218






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53995076%2fhow-to-switch-camera-using-avfoundation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            Npm cannot find a required file even through it is in the searched directory