CodexBloom - Programming Q&A Platform

Encountering a Crash with AVCaptureSession on iOS 16 When Switching Cameras

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-12
ios avfoundation avcapturesession crash Objective-C

I need help solving Hey everyone, I'm running into an issue that's driving me crazy. I've been struggling with this for a few days now and could really use some help. I'm working on an iOS app that uses `AVCaptureSession` to handle camera input, and I've run into a frustrating issue. My app crashes when I attempt to switch from the rear camera to the front camera on devices running iOS 16. The crash occurs during the transition and I see the following error in the console: ``` Terminating app due to uncaught exception 'AVCaptureSessionErrorDomain', reason: 'The session has been stopped.' ``` I've set up the `AVCaptureSession` and the input devices properly, but it seems like the session isn't handling the transition smoothly. Here's a simplified version of the code I’m using to switch cameras: ```objc - (void)switchCamera { AVCaptureDevice *currentDevice = self.currentInput.device; AVCaptureDevice *newDevice = [self cameraWithPosition:(currentDevice.position == AVCaptureDevicePositionBack ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack)]; NSError *error = nil; [self.captureSession beginConfiguration]; [self.captureSession removeInput:self.currentInput]; AVCaptureDeviceInput *newInput = [AVCaptureDeviceInput deviceInputWithDevice:newDevice error:&error]; if (newInput) { [self.captureSession addInput:newInput]; self.currentInput = newInput; } else { NSLog(@"Error adding new input: %@", error.localizedDescription); } [self.captureSession commitConfiguration]; } - (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position { NSArray *devices = [AVCaptureDevice devices]; for (AVCaptureDevice *device in devices) { if (device.position == position) { return device; } } return nil; } ``` I've ensured that the `AVCaptureSession` is indeed running before trying to switch inputs. However, it seems like there's a timing issue since calling `commitConfiguration` after removing the input often leads to the crash. I've tried wrapping the switching logic in a `dispatch_async` to the main queue, but it doesn't seem to help. Is there a best practice for switching camera inputs in `AVCaptureSession` that I might be missing? Any insights would be greatly appreciated! Has anyone else encountered this? I'm working on a service that needs to handle this. How would you solve this? How would you solve this? I'm on Windows 11 using the latest version of Objective-C. What's the correct way to implement this? Am I approaching this the right way?