You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iPadOS 26 - 如何响应应用成为Primary App?

iPadOS 26 - 如何响应应用成为Primary App?

嘿,这个问题我之前在适配iPadOS 26多窗口功能时也碰到过——确实scenePhase的回调不会在主应用切换时触发,得换个方式来监听应用成为“主交互应用”的事件。

下面给你两个实用的实现方案:

  • 利用UIWindowSceneDelegate的激活状态回调
    直接在你的UIWindowSceneDelegate实现里重写windowScene(_:didUpdate:previousActivationState:)方法就行。这个方法会在场景的激活状态发生变化时被调用,刚好能覆盖从非Primary(状态为.foregroundInactive)切换到Primary(状态为.foregroundActive)的场景。

    举个代码例子:

    func windowScene(_ windowScene: UIWindowScene, didUpdate activationState: UISceneActivationState, previousActivationState: UISceneActivationState) {
        // 当应用从非前台活跃状态切换到前台活跃状态时,就是成为了Primary App
        if activationState == .foregroundActive && previousActivationState == .foregroundInactive {
            // 这里写你的响应逻辑,比如刷新UI、恢复交互状态等
            print("应用现在成为Primary App啦!")
        }
    }
    
  • 监听UIScene.activationStateDidChangeNotification通知
    如果你不想把逻辑都塞在Delegate里,也可以通过注册全局通知来监听状态变化。比如在ViewController的初始化阶段注册:

    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册场景激活状态变化的通知
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleSceneActivationChange(_:)),
            name: UIScene.activationStateDidChangeNotification,
            object: nil
        )
    }
    
    @objc private func handleSceneActivationChange(_ notification: Notification) {
        guard let scene = notification.object as? UIWindowScene else { return }
        // 取出之前的激活状态,判断是否从非Primary切换到Primary
        if scene.activationState == .foregroundActive,
           let previousState = notification.userInfo?[UIScene.previousActivationStateUserInfoKey] as? UISceneActivationState,
           previousState == .foregroundInactive {
            // 这里执行你的响应逻辑,比如更新UI、恢复暂停的任务
            updateAppForPrimaryInteraction()
        }
    }
    
    // 记得在页面销毁时移除通知监听,避免内存泄漏
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    

这里要划个重点:iPadOS多窗口模式下,非Primary的前台应用对应的场景激活状态是UISceneActivationState.foregroundInactive,当用户点击你的应用窗口让它成为主交互对象时,状态会切换到.foregroundActive——这就是我们要捕捉的触发点。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 09:03:02