Home > Net >  SwiftUI : onChange(of: scenePhase) is not firing
SwiftUI : onChange(of: scenePhase) is not firing

Time:10-18

I am working on a project with SwiftUI and having trouble with receiving events such as app entering foreground and background. The events are simply not firing at all. Please refer to the code below.

import SwiftUI

@main
struct testApp: App {
    
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onChange(of: scenePhase) { phase in
                    if phase == .background {
                        print("background")
                    }
                    if phase == .active {
                        print("active")
                    }
                    if phase == .inactive {
                        print("inactive")
                    }
                    
                }
        }
    }
}

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!").padding()
    }
}

Xcode version is 12.5 and running this on iOS 14.0 - 14.5 simulator. I tried it on iOS 15 and it worked fine. Is this some kind of a bug in iOS 14?

I am very new to developing iPhone apps. Any help would be appreciated.

CodePudding user response:

You can use .onReceive() with notification publishers you need.

CodePudding user response:

It somehow started working after reinstalling Xcode. My apologies. Thank you for your help!

  • Related