RabHat
RabHat

Reputation: 21

Why does AVCaptureDevice.default return nil in swiftui?

I've been trying to create my own in-built camera but it's crashing when I try to set up the device.

func setUp() {
        do {
            
            self.session.beginConfiguration()
            
            let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .front)
            
            let input = try AVCaptureDeviceInput(device: device!)
            
            if self.session.canAddInput(input) {
                self.session.addInput(input)
            }
            
            if self.session.canAddOutput(self.output) {
                self.session.addOutput(self.output)
            }
            
            self.session.commitConfiguration()
        } catch {
            print(error.localizedDescription)
        }
    }

When I execute the program, it crashed with the input because I try to force unwrap a nil value which is device. I have set the required authorization so that the app can use the camera and it still end up with a nil value.

If anyone has any clue how to solve the problem it would be very appreciate

Upvotes: 2

Views: 746

Answers (1)

Rob Napier
Rob Napier

Reputation: 299325

You're asking for a builtInDualCamera, i.e. one that supports:

  • Automatic switching from one camera to the other when the zoom factor, light level, and focus position allow.
  • Higher-quality zoom for still captures by fusing images from both cameras.
  • Depth data delivery by measuring the disparity of matched features between the wide and telephoto cameras.
  • Delivery of photos from constituent devices (wide and telephoto cameras) from a single photo capture request.

And you're requiring it to be on the front of the phone. I don't know any iPhone that has such a camera on the front (particularly the last one). You likely meant to request position: .back like in the example code. But keep in mind that not all phones have a dual camera on the back either.

You might want to use default(for:) to request the default "video" camera rather than requiring a specific type of camera. Alternately, you can use a AVCaptureDevice.DiscoverSession to find a camera based on specific characteristics.

Upvotes: 2

Related Questions