Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách phát hiện app iOS đang ở Background hay Foreground

Để biết ứng dụng đang ở trạng thái Foreground (Active/Inactive) hay Background, dùng UIApplication.shared.applicationState.

Application State Enum


enum UIApplication.State: Int {
    case active      // Foreground, nhận sự kiện (touch, timer...)
    case inactive    // Foreground, KHÔNG nhận sự kiện (coming call, control center...)
    case background  // Background, có thể bị suspend
}

Kiểm tra trạng thái hiện tại


let state = UIApplication.shared.applicationState

switch state {
case .active:
    print("App đang Active (Foreground, nhận event)")
case .inactive:
    print("App Inactive (Foreground nhưng không nhận event - ví dụ: gọi điện đến, pull down Control Center)")
case .background:
    print("App đang Background")
}

Kết quả chạy trong viewDidLoad

Cách phát hiện app iOS đang ở Background hay Foreground

Phát hiện chuyển đổi trạng thái (Best Practice)

Thay vì poll applicationState, hãy quan sát Notification hoặc implement AppDelegate/SceneDelegate lifecycle:

Cách 1: NotificationCenter (bất kỳ đâu trong app)


// Foreground
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), 
    name: UIApplication.willEnterForegroundNotification, object: nil)

// Background
NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), 
    name: UIApplication.didEnterBackgroundNotification, object: nil)

@objc func appWillEnterForeground() { print("Sắp về Foreground") }
@objc func appDidEnterBackground() { print("Đã vào Background") }

// Deinit: remove observers

Cách 2: SceneDelegate (iOS 13+, khuyến khích)


func sceneWillEnterForeground(_ scene: UIScene) { /* App sắp active */ }
func sceneDidEnterBackground(_ scene: UIScene) { /* App vào background */ }
func sceneWillResignActive(_ scene: UIScene) { /* App sắp inactive */ }
func sceneDidBecomeActive(_ scene: UIScene) { /* App đã active */ }

Cách 3: AppDelegate (Legacy)


func applicationWillEnterForeground(_ application: UIApplication) { }
func applicationDidEnterBackground(_ application: UIApplication) { }
func applicationWillResignActive(_ application: UIApplication) { }
func applicationDidBecomeActive(_ application: UIApplication) { }

Ứng dụng thực tế

  • Tạm dừng video/âm thanh khi vào background.
  • Lưu dữ liệu, sync server khi vào background.
  • Refresh UI, resume task khi về foreground.
  • VoIP, music player: cần Background Modes > Audio, AirPlay để chạy nền.