Swift: How to access in AppDelegate variable from the View controller? Swift: How to access in AppDelegate variable from the View controller? swift swift

Swift: How to access in AppDelegate variable from the View controller?


Your question is full of confusion but if that's what you are looking for:

You can access the appDelegate by getting a reference to it like that:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

after that if you have store a property called lastPoint in your appDelegate you can access its components very simply like that:

let x = appDelegate.lastPoint.xlet y = appDelegate.lastPoint.y

If you need to access your viewController properties from the AppDelegate, then I suggest having a reference to your view controller in your appdelegate:

var myViewController: ViewController!

then when your view controller is created you can store a reference to it in the appdelegate property:

If your create your view controller outside of your appDelegate:

Swift 1-2 syntax

var theViewController = ViewController()let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegateappDelegate.myViewController = theViewController

Swift 3-4 syntax

var theViewController = ViewController()let appDelegate = UIApplication.shared.delegate as! AppDelegateappDelegate.myViewController = theViewController

If you create your view controller inside of your appDelegate:

self.myViewController = ViewController()

After that you can access your data from your viewcontroller from your appdelegate just by accessing its property like that:

let x = self.myViewController.lastPoint.xlet y = self.myViewController.lastPoint.y


Swift 3 Update

    var theViewController = ViewController()    let appDelegate = UIApplication.shared.delegate as! AppDelegate    appDelegate.myViewController = theViewController


You can create a BaseViewController and write this

class BaseViewController {  lazy var appDelegate : AppDelegate {     return UIApplication.shared.delegate as? AppDelegate  }}

and inherit other viewcontrollers with BaseViewController and access this by

class ViewController : BaseViewController {override func viewDidLoad() {    super.viewDidLoad()    print(self.appDelegate?.lastPoint.x)    print(self.appDelegate?.lastPoint.x)}}