9.7 C
New York
Tuesday, March 25, 2025

swiftui – iOS app crash when each .backgroundTask() and .scenePhase in App file


I have been having hassle with .backgroundTask(.appRefresh()) inflicting an intermittent crash when my app is launched. When the crash occurs, the app flashes a darkened display screen with the house display screen gadget info (time-of-day, battery life, and so on) weirdly pivoted panorama and right-justified. This display screen reveals for a split-second, disappears, and the app does NOT launch. Re-tapping the app icon will usually re-launch the app with out incident. After a lot trouble-shooting, I’ve found that commenting out EITHER @Atmosphere(.scenePhase) non-public var part or the .backgroundTask(.appRefresh()) {} code eliminates the crash, so it is one way or the other attributable to having each current on the similar time. As you possibly can see within the instance beneath, it is not even needed to truly use .scenePhase or .backgroundTask to run every other code with a purpose to create the crash.

The next minimal reproducible instance will create the crash on an precise gadget, though you might must launch and stop the app in fast succession 10-20 occasions to see the crash. (I notice most customers aren’t seemingly to try this – typically the crash happens within the precise app on the primary launch. However it’s an intermittent downside so could require a number of testing rounds to seem.)

Along with the code proven right here, I’ve added the “Background Modes” functionality with “Background Fetch” to “Signing & Capabilities” and added the “UpdateBadge” activity to “Data” as a “Permitted background activity scheduler identifier”.

Any thought what may very well be inflicting the crash and the right way to forestall it?

struct ToyBackgroundTasksApp: App {
    
    @Atmosphere(.scenePhase) non-public var part
    
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Item.self,
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return attempt ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Couldn't create ModelContainer: (error)")
        }
    }()

    var physique: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
        .backgroundTask(.appRefresh("UpdateBadge")) {
            print("background activity")
        }
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles