我希望能够运行一个函数来告诉我应用程序何时从冷启动。我能够检测到应用程序何时来自冷启动,但我无法实际运行视图控制器中的功能,我什至希望在 viewdidAppear 之前运行它。
import UIKit
protocol AppLaunchDelegate: AnyObject {
func appDidLaunchFromColdStart()
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
weak var appLaunchDelegate: AppLaunchDelegate?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Check if the app is launching from a cold start
if launchOptions?[.source] == nil {
// This is a cold start
appLaunchDelegate?.appDidLaunchFromColdStart()
}
return true
}
}
class YourViewController: UIViewController, AppLaunchDelegate {
var didLaunchFromColdStart = false
override func viewDidLoad() {
super.viewDidLoad()
// Set the app delegate's delegate to self
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.appLaunchDelegate = self
}
}
// Implement the delegate method
func appDidLaunchFromColdStart() {
print("App launched from a cold start in the view controller")
didLaunchFromColdStart = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if didLaunchFromColdStart {
print("Code executed before viewDidAppear for a cold start")
didLaunchFromColdStart = false
}
}
}
这里的问题是应用程序委托无法访问视图控制器中事件的时间。好消息是,视图控制器显然可以访问其自身事件的时间。
同样,应用程序委托也无法神奇地看到视图控制器。但所有视图控制器都可以神奇地看到应用程序委托。
所以只要扭转你的沟通方向即可。将一个函数放入应用程序委托中,该函数知道这是否是冷启动,并让视图控制器从其任何标准事件实现中调用该函数(以最适合您的时间为准)。