iOS/UIKit

[iOS / UIKit] How to detect when the application state become foreground from the background in ViewController not SceneDelegate

TDCIAN 2023. 3. 3. 19:15

안녕하세요!

오늘은 앱이 background 상태에 있다가 foreground로 올라오는 것을

SceneDelegate가 아니라 ViewController에서 확인하는 방법을 알아봅시다!

 

 

 

다들 아시다시피 SceneDelegate를 통해 우리는 앱이 Background에서 Foreground로 넘어오는 것을 확인할 수 있습니다.

물론 그 반대도 가능합니다!

 

하지만 특정 ViewController에서 Foreground로 넘어오는 것을 확인하는 게 필요한 상황이 있죠?

 

바로 알아봅시다!

willEnterForegroundNotification 옵저버를 추가해주니

ViewController에서 foreground로 들어오는 상황을 notify 해주는 게 보이네요!

 

그럼 background로 나가는 것도 알 수 있겠네요?

 

바로 해봅시다!

 

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

 

전체 코드입니다!

 

// 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