Crash in AVCaptureDevice.requestAccess in iOS 18 with swift 6

I am facing an issue in iOS 18 that works fine in iOS 17 and earlier.

This happens when you set the project to use Swift 6, if you set swift 5 this will work ok.

The app has the Privacy - Camera Usage Description key in the Info.plist.

It is a wrapper that implements UIViewControllerRepresentable to create the UIViewController. This wrapper is within a view that gets pushed when the user presses a button (see snippet code below).

Sometimes, I get a popup asking for permission to access the camera, and the app crashes immediately. Other times, I don’t see the popup, and the app crashes right away.

I tried adding Task { @MainActor } within the requestAccess closure, but it did not resolve the issue. It does not matter the code within the closure; it crashes even if the closure is empty.

The crash trace shows _dispatch_assert_queue_fail (see the attached image).

Has anyone else experienced this issue? Any insights would be greatly appreciated.

The following code will crash if run as is.

***** Please add the Privacy - Camera Usage Description key in the Info.plist to prevent this issue.

import SwiftUI
import AVFoundation

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")

            ViewControllerWrapper()
        }
    }
}

struct ViewControllerWrapper: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> ViewController {
        ViewController()
    }

    func updateUIViewController(_ viewController: ViewController, context: Context) {}
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        AVCaptureDevice.requestAccess(for: .video) { _ in

        }
    }
}
Answered by luchi2300 in 825048022

I found a potential fix for this issue: The async method needs to be called instead of the one with the completion handler.

Task { let accessIsGranted = await AVCaptureDevice.requestAccess(for: .video) }

Accepted Answer

I found a potential fix for this issue: The async method needs to be called instead of the one with the completion handler.

Task { let accessIsGranted = await AVCaptureDevice.requestAccess(for: .video) }

Crash in AVCaptureDevice.requestAccess in iOS 18 with swift 6
 
 
Q