Computer >> 컴퓨터 >  >> 프로그램 작성 >> IOS

iOS 프로그램이 전경 또는 배경에 있는지 확인하는 방법은 무엇입니까?

<시간/>

애플리케이션이 포그라운드 또는 백그라운드에 있을 때를 아는 것은 iOS 개발자로서 백그라운드 다운로드, 앱이 포그라운드로 전환되는 경우 이벤트와 같은 여러 이벤트를 처리해야 하므로 중요합니다.

여기에서 애플리케이션이 백그라운드에 있는지 포그라운드에 있는지 확인하는 방법을 살펴보겠습니다.

이를 위해 알림 센터를 사용할 것입니다.

이에 대한 자세한 내용은 Apple 문서를 참조하십시오.

https://developer.apple.com/documentation/foundation/notificationcenter

등록된 관찰자에게 정보를 브로드캐스트할 수 있는 알림 디스패치 메커니즘입니다. 우리는 같은 것에 관찰자를 추가하고 전화를 받을 것입니다.

1단계 − Xcode 열기 → 새 프로젝트 → 단일 보기 응용 프로그램 → 이름을 "ForegroundBackground"로 지정합니다.

2단계 − viewDidLoad에서 알림 센터의 개체를 만듭니다.

let notificationCenter = NotificationCenter.default

3단계 − 배경 및 전경에 대한 관찰자 추가

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

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

4단계 − 선택기 방법 구현

@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!")
   }
}