Чтобы получить доступ к AppDelegate из ViewController в Swift, вы можете использовать следующие методы:
Метод 1: использование свойства UIApplication.shared.delegate
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
// Access the AppDelegate properties and methods here
// For example: appDelegate.someMethod()
}
Метод 2: использование протокола UIApplicationDelegate
if let appDelegate = UIApplication.shared.delegate as? YourAppDelegateClassName {
// Access the AppDelegate properties and methods here
// For example: appDelegate.someMethod()
}
с фактическим именем класса вашего AppDelegate.
Метод 3: использование ссылки, переданной из AppDelegate в ViewController
В AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let viewController = ViewController()
viewController.appDelegate = self
// ...
return true
}
В ViewController:
class ViewController: UIViewController {
weak var appDelegate: AppDelegate?
// Access the AppDelegate properties and methods using `appDelegate`
// For example: appDelegate?.someMethod()
// ...
}