Cannot use Scene methods for URL, NSUserActivity, and other External Events without using SwiftUI Lifecycle

Viewed 816

I am using the new "pure" SwiftUI App and Scene structs instead of an AppDelegate.

Some of my views accept custom url schemes and user activities using onOpenURL(perform:). Everything works as expected.

However, starting with Beta 6, Xcodes gives the following runtime warning:

runtime: SwiftUI: Cannot use Scene methods for URL, NSUserActivity, and other External Events without using SwiftUI Lifecycle. Without SwiftUI Lifecycle, advertising and handling External Events wastes resources, and will have unpredictable results.

What exactly am I doing wrong? What is SwiftUI Lifecycle referring to?


This is what my main App struct looks like. I am attaching some default modifiers to the main view.

@main
struct MyApp: App {
    @StateObject var viewModel = GlobalViewModel()
    
    var body: some Scene {
        WindowGroup {
            MainView()
                .applyingDefaultColors()
                .environmentObject(viewModel)
                .environmentObject(TranslationProvider())
                .toggleStyle(SwitchToggleStyle(tint: .accentColor))
        }
    }
}
1 Answers

SwiftUI Lifecycle refers to views that are rendered as children of a Scene, namely the WindowGroup struct that is normally returned in the body of the App.

The implication is basically that if you attach "auxiliary" views to the Scene, such as Commands for MacOS, they can't use methods like .onContinuedUserActivity and will produce this error. Communicating view state changes in these cases should instead use FocusedValues, where the subscribing view has a @FocusedBinding or @FocusedValue, and the publishing view injects .focusedValue(\.someKeyPath, $interestingState)

Related