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)")
}
}
}
}
두가지 방법중에 먼저 호출되는건 첫번째 방법이고 더 익숙한 방법임.
'SwiftUI' 카테고리의 다른 글
[SwiftUI] NotificationCenter 사용하기 (0) | 2024.04.17 |
---|---|
[SwiftUI] App to App / Universal-Link Scheme 처리 이벤트 (0) | 2024.04.17 |
[SwiftUI] AppDelegate 추가해서 Push 설정하기 (0) | 2024.04.17 |
[SwiftUI] TextField 화면 터치로 키보드 내리기(전역설정) (0) | 2024.04.17 |
[SwiftUI] UIView <-> SwiftUI View 호출 방법 (0) | 2024.04.12 |