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

iOS:如何让sceneWillEnterForeground仅在未点击通用链接时发通知

解决方案

在SceneDelegate类中添加一个标记变量,用来区分是否通过通用链接触发应用唤醒或启动,以此控制update通知的发送时机:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    // 新增私有标记,默认值为false,表示未触发通用链接
    private var didTriggerUniversalLink = false
    
    func sceneWillEnterForeground(_ scene: UIScene) {
        print("... sceneWillEnterForeground ALWAYS CALLED")
        // 仅当未触发通用链接时,发送update通知
        if !didTriggerUniversalLink {
            NotificationCenter.default.post(name: Notification.Name("update"), object: nil)
        }
        // 重置标记,避免影响后续场景切换逻辑
        didTriggerUniversalLink = false
    }
    
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        print("SCENE WITH UNIVERSAL LINK CLICK")
        // 标记当前为通用链接触发的场景
        didTriggerUniversalLink = true
        guard let url = userActivity.webpageURL else { return }
        let userInfo: [String: String] = ["url": url.absoluteString]
        NotificationCenter.default.post(name: NSNotification.Name("universalLink"), object: nil, userInfo: userInfo)
    }
}

逻辑说明

  • 点击通用链接时,scene(_:continue:)会先于sceneWillEnterForeground执行(无论应用是从后台唤醒还是冷启动),此时会将didTriggerUniversalLink设为true。
  • 进入sceneWillEnterForeground时,通过标记变量判断,仅在非通用链接场景下发送update通知,执行完成后重置标记,确保下次场景切换不受影响。

多场景适配(iPadOS多窗口)

如果应用支持多窗口场景,可以把标记与具体UIScene绑定,避免不同窗口间的逻辑干扰:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    private var sceneUniversalLinkFlags: [UIScene: Bool] = [:]
    
    func sceneWillEnterForeground(_ scene: UIScene) {
        let isTriggered = sceneUniversalLinkFlags[scene, default: false]
        if !isTriggered {
            NotificationCenter.default.post(name: Notification.Name("update"), object: nil)
        }
        sceneUniversalLinkFlags[scene] = false
    }
    
    func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        sceneUniversalLinkFlags[scene] = true
        guard let url = userActivity.webpageURL else { return }
        let userInfo: [String: String] = ["url": url.absoluteString]
        NotificationCenter.default.post(name: NSNotification.Name("universalLink"), object: nil, userInfo: userInfo)
    }
}

内容的提问来源于stack exchange,提问作者Sankalp Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:52:36