ios – @Observable vs @MainActor return Call to main actor-isolated initializer ‘init()’ in a synchronous nonisolated context


I’m working with DataScannerViewController to give the user the ability to recognize text using the camera.

I created a template to manage camera permissions.

I uses @Observable macro and I need to use it on the main tread also using @MainActor macro

Now the problem is that the compiler gives me an error:

Call to main actor-isolated initializer ‘init()’ in a synchronous
nonisolated context

at this line @State private var scannerViewModel = ScannerViewModel()

How can this problem be solved?

It seems that @MainActor conflicts with @Observable

This is the code


import Foundation
import VisionKit

enum ScannerStatus {
    case notDeterminated, denied, cameraNotAvailable, scannerNotAvailable, available
}

@MainActor
@Observable
final class ScannerViewModel {
    var accessStatus: ScannerStatus = .notDeterminated
    var scannerAvailable: Bool {
            DataScannerViewController.isSupported &&
            DataScannerViewController.isAvailable
        }
}


@main
struct FindTextFromImageApp: App {

@State private var scannerViewModel = ScannerViewModel() // Call to main actor-isolated initializer 'init()' in a synchronous  nonisolated context

var body: some Scene {
    WindowGroup {
        Start()
            .environment(scannerViewModel)
    }
}

}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img