Files
youle_app_ios_v2/ylgamehall/Source/Resource/AppLifecycleObserver.swift
T

51 lines
1.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// AppLifecycleObserver.swift
// ylgamehall
//
// 监听 UIApplication 前/后台切换通知,提供 onBackground / onForeground 钩子。
//
// 契约:docs/H5-Native-Contract.md §3.2 4appservice 反向 callback
// "2" = 进入后台 / "1" = 回到前台(值错位沿用历史 msext WKWebView 路径,
// 参 daoqi/msext NewRootVC.m:1773/1782、gameController.m:1323/1332
// Phase 2.11
//
import UIKit
@MainActor
public final class AppLifecycleObserver {
public static let shared = AppLifecycleObserver()
public var onBackground: (@MainActor () -> Void)?
public var onForeground: (@MainActor () -> Void)?
private var started = false
public init() {}
public func start() {
guard !started else { return }
started = true
let nc = NotificationCenter.default
nc.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil,
queue: .main
) { [weak self] _ in
MainActor.assumeIsolated {
self?.onBackground?()
}
}
nc.addObserver(
forName: UIApplication.willEnterForegroundNotification,
object: nil,
queue: .main
) { [weak self] _ in
MainActor.assumeIsolated {
self?.onForeground?()
}
}
}
}