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

如何在自定义静态类中捕获iOS应用级事件(如applicationDidBecomeActive)

解决方案:让CustomClass直接监听应用生命周期事件

没问题,我来给你几个实用的方案,让你的CustomClass能直接监听并处理应用级生命周期事件,不用再依赖AppDelegate的方法啦:

方案1:使用NotificationCenter(兼容所有iOS版本)

这是最通用的做法,通过系统通知中心订阅应用生命周期事件,在CustomClass内部处理回调:

import UIKit

class CustomClass {
    static var IS_ACTIVE: Bool = false
    
    // 单例模式确保监听只注册一次
    static let shared = CustomClass()
    private init() {
        setupNotificationListeners()
    }
    
    private func setupNotificationListeners() {
        // 订阅应用激活事件
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onAppDidBecomeActive),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
        
        // 订阅应用进入后台事件
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onAppWillResignActive),
            name: UIApplication.willResignActiveNotification,
            object: nil
        )
        
        // 订阅应用即将终止事件
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(onAppWillTerminate),
            name: UIApplication.willTerminateNotification,
            object: nil
        )
    }
    
    @objc private func onAppDidBecomeActive() {
        CustomClass.IS_ACTIVE = true
        print("应用已激活,IS_ACTIVE设为true")
    }
    
    @objc private func onAppWillResignActive() {
        CustomClass.IS_ACTIVE = false
        print("应用即将进入后台,IS_ACTIVE设为false")
    }
    
    @objc private func onAppWillTerminate() {
        CustomClass.IS_ACTIVE = false
        print("应用即将终止,IS_ACTIVE设为false")
    }
}

说明:

  • 用单例模式初始化CustomClass,确保通知监听只会被注册一次,避免重复回调。
  • 第一次访问CustomClass.shared时,初始化方法会自动注册所有监听。
  • 单例对象在应用运行期间不会被释放,因此不需要手动移除观察者,应用终止时系统会自动清理。

方案2:iOS 17+ 使用App生命周期Observability API(更现代的写法)

如果你的应用目标版本是iOS 17及以上,可以使用苹果提供的新API,代码更简洁,不需要依赖通知中心:

import UIKit

class CustomClass {
    static var IS_ACTIVE: Bool = false
    
    static let shared = CustomClass()
    private init() {
        observeAppLifecycle()
    }
    
    private func observeAppLifecycle() {
        Task {
            // 异步监听应用状态变化
            for await phase in UIApplication.shared.phaseUpdates {
                switch phase {
                case .active:
                    CustomClass.IS_ACTIVE = true
                    print("应用进入激活状态")
                case .inactive, .background, .terminated:
                    CustomClass.IS_ACTIVE = false
                    print("应用离开激活状态:\(phase)")
                @unknown default:
                    // 处理未来可能新增的状态
                    break
                }
            }
        }
    }
}

说明:

  • 利用Async/Await和异步序列phaseUpdates,以更现代的Swift风格监听状态变化。
  • 不需要手动管理观察者,代码逻辑更清晰。

方案3:使用Combine框架(适合响应式项目)

如果你的项目已经在使用Combine,可以通过订阅通知的publisher来处理事件:

import UIKit
import Combine

class CustomClass {
    static var IS_ACTIVE: Bool = false
    private var cancellables = Set<AnyCancellable>()
    
    static let shared = CustomClass()
    private init() {
        setupCombineSubscriptions()
    }
    
    private func setupCombineSubscriptions() {
        // 订阅应用激活事件
        NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
            .sink { _ in
                CustomClass.IS_ACTIVE = true
                print("应用激活(Combine)")
            }
            .store(in: &cancellables)
        
        // 订阅应用进入后台事件
        NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
            .sink { _ in
                CustomClass.IS_ACTIVE = false
                print("应用即将进入后台(Combine)")
            }
            .store(in: &cancellables)
        
        // 订阅应用即将终止事件
        NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)
            .sink { _ in
                CustomClass.IS_ACTIVE = false
                print("应用即将终止(Combine)")
            }
            .store(in: &cancellables)
    }
}

说明:

  • 用Combine的响应式编程风格处理事件,适合已经采用Combine架构的项目。
  • cancellables集合用来管理订阅的生命周期,确保订阅在对象释放时被取消。

注意事项

  • 如果你不需要单例,也可以在CustomClass的静态初始化器里注册监听,但要注意避免重复注册。
  • 对于非单例的CustomClass实例,记得在deinit方法中移除NotificationCenter的观察者,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Ankur Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:27:09