I want to be able to run a function that tells me when the app is coming from cold start. I was able to detect when the app is coming from cold start but I'm not able to actually run the function that is in the view controller, I'm hoping to even run it before 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
}
}
}
The problem here is that the app delegate has no access to the timing of events in the view controller. The good news is that the view controller does have access to the timing of its own events, obviously.
Similarly, the app delegate cannot magically see the view controllers. But all view controllers can magically see the app delegate.
So just reverse the direction of your communication. Put a function into the app delegate which knows whether this was a cold launch, and have the view controller call that function from any of its standard event implementations (whichever fits the timing best for you).