Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - How to get access to "WindowScene"

Tags:

xcode

swiftui

In watching the WWDC 21 videos reference StoreKit 2, there are a few functions that they reference wherein they let a value = WindowScene as follows:

func manageSubscriptions() async {
    if let windowScene = self.view.window?.windowScene {
        do {
            try await AppStore.showManageSubscriptions(in: windowScene)
        } catch {
            //error
        }
    }
}

The let line errors out with the message: Type of expression is ambiguous without more context

If I try and provide more context with something like:

if let windowScene = (self.view.window?.windowScene)! as UIWindowScene {

I am told: Value of type 'MyStruct' has no member 'view'

What am I missing, must be something simple, to gain access to this needed UI element?

Thank you

Added: I'd like to add that I am using a SwiftUI app that was created using a SceneDelegate and AppDelegate, not a simple struct: App, type of structure. So I am guessing I need to access something in the SceneDelegate to get the right object..

like image 487
JerseyDevel Avatar asked Feb 04 '26 11:02

JerseyDevel


2 Answers

Just to provide an answer for anyone interested, with all credit to @aheze for finding it and @Matteo Pacini for the solution, to get this specific method to work when using a SwiftUI app that has an AppDelegate/SceneDelegate structure, this will work:

@MainActor
func manageSubscriptions() async {
    if let windowScene = UIApplication.shared.connectedScenes.first {
        do {
            try await AppStore.showManageSubscriptions(in: windowScene as! UIWindowScene)
        } catch {
            //error
        }
    }
}
like image 57
JerseyDevel Avatar answered Feb 09 '26 08:02

JerseyDevel


You can conversely use the view modifier manageSubscriptionsSheet(isPresented:) instead. This is Apple's recommended approach when using SwiftUI and will mitigate the need for getting a reference to the window scene.

Source:

If you’re using SwiftUI, call the manageSubscriptionsSheet(isPresented:)view modifier.

like image 24
HGDev Avatar answered Feb 09 '26 07:02

HGDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!