안녕하세요!
오늘은 앱이 background 상태에 있다가 foreground로 올라오는 것을
SceneDelegate가 아니라 ViewController에서 확인하는 방법을 알아봅시다!

다들 아시다시피 SceneDelegate를 통해 우리는 앱이 Background에서 Foreground로 넘어오는 것을 확인할 수 있습니다.
물론 그 반대도 가능합니다!
하지만 특정 ViewController에서 Foreground로 넘어오는 것을 확인하는 게 필요한 상황이 있죠?
바로 알아봅시다!

willEnterForegroundNotification 옵저버를 추가해주니
ViewController에서 foreground로 들어오는 상황을 notify 해주는 게 보이네요!
그럼 background로 나가는 것도 알 수 있겠네요?
바로 해봅시다!

다시 foreground로 복귀해보겠습니다!

전체 코드입니다!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ViewController.swift | |
// DetectingAppState | |
// | |
// Created by JeongminKim on 2023/03/01. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
print("ViewController.swift - viewDidLoad") | |
// MARK: Add observer name 'willEnterForegroundNotification' | |
NotificationCenter.default.addObserver( | |
forName: UIApplication.willEnterForegroundNotification, | |
object: nil, | |
queue: .main | |
) { notification in | |
print("ViewController.swift - willEnterForegroundNotification") | |
} | |
// MARK: Add observer name 'didEnterBackgroundNotification' | |
NotificationCenter.default.addObserver( | |
forName: UIApplication.didEnterBackgroundNotification, | |
object: nil, | |
queue: .main | |
) { notification in | |
print("ViewController.swift - didEnterBackgroundNotification") | |
} | |
} | |
} | |
GitHub에서 Code를 Download 받으실 수 있습니다!
https://github.com/TDCIAN/DetectingAppState
GitHub - TDCIAN/DetectingAppState
Contribute to TDCIAN/DetectingAppState development by creating an account on GitHub.
github.com
'iOS > UIKit' 카테고리의 다른 글
[iOS / UIKit] How to use Action Sheets (0) | 2023.03.05 |
---|---|
[iOS / UIKit] How to set cornerRadius for specific corners (0) | 2023.03.04 |
[iOS / UIKit] How to change UIPickerView Selected Background Color (0) | 2023.03.02 |
[iOS / UIKit] How to send email Swift (0) | 2023.02.13 |
[iOS / UIKit] How to use PreviewProvider in UIKit (0) | 2023.02.12 |