I'm currently developing an application using SwiftUI.
I want to use a method when a view appears.
In the case of the code I attached below, I can use the print
method when the app is booted and done some transitions between pages.
But I want to use the print
method when I reopen the app like below:
1: run the code on a simulator (I can see the
print
method works).2: press a home button.
3: open the app with tap the app icon (I can't see the
print
method works ).(*) I want to use the
print
method here.
How can I do it as I want in this case?
here is the code:
import SwiftUI
struct ContentView: View {
@State private var selection = 0
var body: some View {
TabView(selection: $selection){
Text("First View")
.onAppear(){
print("First")
}
.tabItem {
Text("First")
}
.tag(0)
Text("Second View")
.tabItem {
Text("Second")
}
.tag(1)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
ADD:
I found a way to use some function when the app becomes a foreground from a background using sceneWillEnterForeground
or sceneWillResignActive
in SceneDelegate.swift
But in this case, when the app becomes a foreground with the SecondView also works function. And I want to modify the code to work the function only when the app becomes foreground with the FirstView.
Is there any way to do that?
SceneDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
print("BecomeActive")
}
func sceneWillEnterForeground(_ scene: UIScene) {
print("Foreground")
}
Xcode: Version 11.7
Swift: Swift 5