SwiftUI
[SwiftUI] View 백그라운드/포그라운드 이벤트 체크
삽질중
2024. 4. 17. 10:50
swiftui 프로젝트 생성시 아래 4개의 이벤트를 사용하고 싶은데 어떻게 설정하는지 몰라 찾아 봤음.
willResignActiveNotification
willEnterForegroundNotification
didBecomeActiveNotification
didEnterBackgroundNotification
@main
struct SwiftUIComponemtApp: App {
var body: some Scene {
WindowGroup {
ContentView()
// MARK: 백그라운드/포그라운드
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
log(direction: .ETC, ofType: self, datas: "willResignActiveNotification")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
log(direction: .ETC, ofType: self, datas: "willEnterForegroundNotification")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
log(direction: .ETC, ofType: self, datas: "didBecomeActiveNotification")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
log(direction: .ETC, ofType: self, datas: "didEnterBackgroundNotification")
}
}
}
}
또는
struct ContentView: View {
@Environment(\.scenePhase) private var scenePhase
var body: some View {
Text("Live Main View!!!")
.onChange(of: scenePhase) { newPhase in
switch newPhase {
case .background:
print("SchenePhase: Background from \(newPhase)")
case .inactive:
print("SchenePhase: Inactive from \(newPhase)")
case .active:
print("SchenePhase: Active/Foreground from \(newPhase)")
@unknown default:
print("SchenePhase: Unknown scene phase \(newPhase)")
}
}
}
}
두가지 방법중에 먼저 호출되는건 첫번째 방법이고 더 익숙한 방법임.