如何檢查iOS程式是否處於前臺或後臺?
瞭解應用程式何時處於前臺或後臺非常重要,因為作為 iOS 開發人員,我們需要處理多個事件,例如後臺下載以及應用程式轉到前臺時的事件。
在這裡,我們將瞭解如何檢查應用程式是否處於後臺或前臺。
我們將為此使用通知中心。
要了解更多資訊,您可以參考蘋果文件。
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!")
}
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP