在 applicationWillTerminate() 中找出应用程序在哪个视图上终止
Find out which view the application was terminated on in applicationWillTerminate()
假设我的应用程序中有多个屏幕:View1
、View2
等
如果用户在某个屏幕上,比如 View3
,应用程序终止是因为用户退出应用程序等,我知道 applicationWillTerminate(_ application: UIApplication)
会被调用,但我怎么知道在应用程序终止之前用户在哪个视图上?
我需要这样的功能:
func applicationWillTerminate(_ application: UIApplication) {
let viewUserIsOn = getViewUserWasOnWhenAppQuit()
switch viewUserIsOn{
case .view1:
doThisIfOnView1()
case .view2:
doThisIfOnView2()
default:
doNothing()
}
}
如果视图按顺序出现,您可以这样做:
class Settings: ObservableObject {
static let shared = Settings()
@Published var viewType: ViewType!
}
enum ViewType {
case view1, view2, view3
}
struct View1: View {
@ObservedObject var settings = Settings.shared
var body: some View {
[...]
.onAppear {
settings.viewType = .view1
}
}
}
struct View2: View {
@ObservedObject var settings = Settings.shared
var body: some View {
[...]
.onAppear {
settings.viewType = .view2
}
}
}
// same for View 3
func applicationWillTerminate(_ application: UIApplication) {
switch Settings.shared.viewType {
case .view1: // View 1 was displayed
case .view2: // View 2 was displayed
case .view3: // View 3 was displayed
}
}
假设我的应用程序中有多个屏幕:View1
、View2
等
如果用户在某个屏幕上,比如 View3
,应用程序终止是因为用户退出应用程序等,我知道 applicationWillTerminate(_ application: UIApplication)
会被调用,但我怎么知道在应用程序终止之前用户在哪个视图上?
我需要这样的功能:
func applicationWillTerminate(_ application: UIApplication) {
let viewUserIsOn = getViewUserWasOnWhenAppQuit()
switch viewUserIsOn{
case .view1:
doThisIfOnView1()
case .view2:
doThisIfOnView2()
default:
doNothing()
}
}
如果视图按顺序出现,您可以这样做:
class Settings: ObservableObject {
static let shared = Settings()
@Published var viewType: ViewType!
}
enum ViewType {
case view1, view2, view3
}
struct View1: View {
@ObservedObject var settings = Settings.shared
var body: some View {
[...]
.onAppear {
settings.viewType = .view1
}
}
}
struct View2: View {
@ObservedObject var settings = Settings.shared
var body: some View {
[...]
.onAppear {
settings.viewType = .view2
}
}
}
// same for View 3
func applicationWillTerminate(_ application: UIApplication) {
switch Settings.shared.viewType {
case .view1: // View 1 was displayed
case .view2: // View 2 was displayed
case .view3: // View 3 was displayed
}
}