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

Kiểm tra app iOS đang ở foreground hay background

Dùng NotificationCenter quan sát UIApplication.willResignActiveNotification (vào background) và UIApplication.didBecomeActiveNotification (vào foreground).

let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)
nc.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!") }

Đặt breakpoint trong các selector để debug.