Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธาตรวจสอบว่าแอป iOS อยู่ Foreground หรือ Background

ใช้ UIApplication.shared.applicationState ตรวจสอบสถานะแอป

Application State Enum


enum UIApplication.State: Int {
    case active      // Foreground, รับ Event ได้
    case inactive    // Foreground, ไม่รับ Event (Call, Control Center)
    case background  // Background
}

การตรวจสอบพื้นฐาน


let state = UIApplication.shared.applicationState

switch state {
case .active:
    print("🟢 Active (Foreground)")
case .inactive:
    print("🟡 Inactive (Foreground แต่ไม่ Active)")
case .background:
    print("🔴 Background")
@unknown default: break
}

ใช้กับ App Delegate / Scene Delegate (แนะนำ)

แทนที่จะ Poll สถานะ ให้ใช้ Delegate Methods:


// AppDelegate (iOS 12 และก่อน)
func applicationDidBecomeActive(_ application: UIApplication) { /* Foreground */ }
func applicationWillResignActive(_ application: UIApplication) { /* จะ Inactive */ }
func applicationDidEnterBackground(_ application: UIApplication) { /* Background */ }
func applicationWillEnterForeground(_ application: UIApplication) { /* จะ Foreground */ }

// SceneDelegate (iOS 13+)
func sceneDidBecomeActive(_ scene: UIScene) { }
func sceneWillResignActive(_ scene: UIScene) { }
func sceneDidEnterBackground(_ scene: UIScene) { }
func sceneWillEnterForeground(_ scene: UIScene) { }

NotificationCenter (สำหรับ View Controller)


override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}

@objc func appDidEnterBackground() { print("App entered background") }
@objc func appWillEnterForeground() { print("App will enter foreground") }

deinit { NotificationCenter.default.removeObserver(self) }

SwiftUI (iOS 14+)


struct ContentView: View {
    @Environment(\.scenePhase) var scenePhase
    
    var body: some View {
        Text("Hello")
            .onChange(of: scenePhase) { newPhase in
                switch newPhase {
                case .active: print("Active")
                case .inactive: print("Inactive")
                case .background: print("Background")
                @unknown default: break
                }
            }
    }
}

Use Cases

  • Pause/Resume Video, Audio, Game
  • Save Draft เมื่อเข้ Background
  • Start/Stop Location Updates
  • Connect/Disconnect WebSocket
  • Analytics: Track Session Duration