Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

ios - Detect when application is terminated in SwiftUI 2.0

I'm working in Swift UI 2.0 and currently have a setup as follows:

@main
struct MyApp: App {
    @Environment(.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
           InitialView()
        }
        .onChange(of: scenePhase) { (newScenePhase) in
            switch newScenePhase {
            case .active:
                print("scene is now active!")
            case .inactive:
                print("scene is now inactive!")
            case .background:
                print("scene is now in the background!")
                
            @unknown default:
                print("sus")
            }
        }
    }
}

which is fine but none of these account for the case when the application is terminated (i.e. a user double taps the home button and swipes up on the app). How can I account for this case?

I tried unsuccessfully implementing applicationWillTerminate(_:) so any guidance here would be appreciated.

Thank you!

question from:https://stackoverflow.com/questions/65868103/detect-when-application-is-terminated-in-swiftui-2-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is something I grabbed from a previous project. You can setup a notification observer to check if the app has "moved to background", so basically when the user exits the app.

 init() {
        let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
    }

Just throw that in your main viewcontroller's init method and...

@objc func appMovedToBackground() {
    print("App moved to background")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...