跳到主要内容

状态切换

问题

App 前后台切换时会触发哪些回调?

答案

UIKit(SceneDelegate)

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// 进入前台(Active)
func sceneDidBecomeActive(_ scene: UIScene) {
// 恢复暂停的任务、刷新 UI
}

// 即将进入后台
func sceneWillResignActive(_ scene: UIScene) {
// 暂停任务、保存数据
}

// 已进入后台
func sceneDidEnterBackground(_ scene: UIScene) {
// 释放共享资源、保存状态
}

// 即将进入前台
func sceneWillEnterForeground(_ scene: UIScene) {
// 准备 UI 更新
}
}

SwiftUI

@main
struct MyApp: App {
@Environment(\.scenePhase) var scenePhase

var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: scenePhase) { _, newPhase in
switch newPhase {
case .active:
print("App 进入前台")
case .inactive:
print("App 即将失活")
case .background:
print("App 进入后台")
@unknown default:
break
}
}
}
}

状态切换顺序

启动 → Inactive → Active
Home 键 → Active → Inactive → Background → Suspended
返回 App → Background → Inactive → Active
来电 → Active → Inactive → (接听) Active(电话) / (拒接) Active

常见面试问题

Q1: Inactive 和 Background 的区别?

答案

  • Inactive:App 在前台但不接收事件(如下拉通知中心、来电弹窗)
  • Background:App 不在前台,有有限执行时间(约 30 秒),之后进入 Suspended

相关链接