Saturday, November 21, 2026
HomeiOS Developmentios - Await StateObject initialization in SwiftUI

ios – Await StateObject initialization in SwiftUI

[ad_1]

I’m engaged on an app that makes use of an AVCaptureLayer to show a video preview layer and likewise a textual content illustration of the brightness (calculated from the video metadata). I’ve tried to make my app extra environment friendly by solely creating one AVCaptureSession in a category VideoStream and I wish to then move the seize session to a UIViewRepresentable that creates a UIView exhibiting the video preview layer. The View is easy:

struct ContentView: View {
    @StateObject var videoStream = VideoStream() // holds session variable for AVCaptureSession
    
    var physique: some View {
        VStack {
            VideoPreviewHolder(runningSession: videoStream.session) // videoStream.session not initialized at construct time
        }.body(width: 300, top: 300, alignment: .heart)
        Textual content(String(format: "%.2f Lux", videoStream.luminosityReading))
            .font(.largeTitle)
    }
    
}

Does SwiftUI present a solution to await the initialization of a StateObject class? The init() technique for VideoStream() calls a operate answerable for first checking for digital camera authorization and if obligatory requesting it, and if authorization is granted then a second operate is known as which configures the AVCaptureSession. This all takes fairly a little bit of time, particularly if the person must grant or deny the authorization.

I’ve tried including await / async to the VideoStream() initializer and the capabilities referred to as therein, however since my VideoStream() class inherits from NSObject, I obtain an error that async initializer can't be represented in Goal-C.

Is there a SwiftUI particular approach of awaiting the StateObject‘s initialization?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments