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

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

รู้สถานะ Foreground/Background สำคัญสำหรับจัดการ Background Downloads, Events

ใช้ NotificationCenter อ่านรายละเอียด

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → New Project → Single View Application → ชื่อ "ForegroundBackground"

ขั้นตอนที่ 2-4: โค้ด ViewController.swift

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

ขั้นตอนที่ 5: ทดสอบ

ตั้ง Breakpoint รันแอป สลับ Foreground/Background จะเห็น Log