Computer >> 컴퓨터 >  >> 프로그래밍 >> iOS

iOS 앱이 포그라운드 또는 백그라운드 상태인지 확인하는 방법

iOS 개발자에게 앱이 현재 포그라운드(foreground)에 있는지 아니면 백그라운드(background)에 있는지 파악하는 것은 매우 중요합니다. 백그라운드 다운로드 처리나 앱이 다시 포그라운드로 전환될 때의 이벤트 처리 등 다양한 상황에서 이 정보가 필요하기 때문입니다.

이 글에서는 NotificationCenter를 활용해 앱이 백그라운드에 있는지 포그라운드에 있는지 확인하는 방법을 단계별로 알아보겠습니다.

NotificationCenter란?

NotificationCenter(알림 센터)는 등록된 옵저버(observer)들에게 정보를 브로드캐스트할 수 있게 해주는 알림 발송 메커니즘입니다. 우리는 여기에 옵저버를 추가하고, 앱 상태가 변경될 때마다 콜백을 받도록 구현할 것입니다.

자세한 내용은 Apple 공식 문서를 참고하세요.
https://developer.apple.com/documentation/foundation/notificationcenter

구현 단계

1단계: 프로젝트 생성

Xcode를 실행하고 새 프로젝트를 만듭니다. Xcode → New Project → Single View Application을 선택하고 프로젝트 이름을 "ForegroundBackground"로 지정합니다.

2단계: NotificationCenter 객체 생성

viewDidLoad 메서드 안에서 NotificationCenter의 기본 인스턴스를 가져옵니다.

let notificationCenter = NotificationCenter.default

3단계: 백그라운드 및 포그라운드 옵저버 추가

앱이 비활성화될 때(willResignActiveNotification)와 활성화될 때(didBecomeActiveNotification) 각각 호출될 옵저버를 등록합니다.

notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)

notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)

4단계: 셀렉터 메서드 구현

옵저버가 호출할 @objc 메서드를 작성합니다.

@objc func foregroundCall() {
    print("App moved to foreground")
}
@objc func backgroundCall() {
    print("App moved to background!")
}

5단계: 실행 및 확인

브레이크포인트를 설정한 후 애플리케이션을 실행합니다. 홈 버튼을 누르거나 앱을 전환하면 콘솔에서 상태 변화 로그를 확인할 수 있습니다.

전체 코드

import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    @objc func foregroundCall() {
        print("App moved to foreground")
    }
    @objc func backgroundCall() {
        print("App moved to background!")
    }
}

마무리

이처럼 NotificationCenter의 willResignActiveNotification과 didBecomeActiveNotification 알림만 활용하면 별도의 복잡한 설정 없이도 앱의 포그라운드/백그라운드 전환 시점을 손쉽게 감지할 수 있습니다. 이 기능은 데이터 동기화, 타이머 일시정지, 푸시 알림 처리 등 실제 앱 개발에서 폭넓게 활용되므로 꼭 익혀두시기 바랍니다.