0

I want to get the ViewController variable From AppDelegate, I tried :

//1.
print(ViewController().strName)

//2.
let vc = ViewController()
print(vc.strName)

//3.
let vc = UIApplication.shared.keyWindow!.rootViewController as! ViewController
print(vc.strName)

All not working, the print value is empty...

The code in ViewController:

var strName : String = ""
override func viewDidLoad() {

    strName = "Tom"

}
Edem
  • 53
  • 5

1 Answers1

0

I suggest to have a check in this link Swift: How to access in AppDelegate variable from the View controller? else try in view controller,

class ViewController: UIViewController {

  var strName = "someString" // some value

}

In AppDelegate,

    var mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    _ = self.window?.rootViewController as? ViewController
    print(mainViewController.strName)
}
AzeTech
  • 623
  • 11
  • 21
  • This has a error message at "let viewController = self.window?.rootViewController as? ViewController" – Edem Mar 25 '19 at 02:42
  • @Edem, check the edited answer now, check whether u have navigation controller in view controller.... I have tried its working and I can print the value in appdelegate (or else try this is did finish launch section in app delegate ) – AzeTech Mar 25 '19 at 06:10
  • @Edem, have you written the var strName = "some value" in your view controller, and did u try in func appdidfinishlaunchsection. Seriously I tried and could print the value...check whether u missed anything.. – AzeTech Mar 25 '19 at 08:14
  • Yes, as my post, I wrote it in viewdidload. – Edem Mar 25 '19 at 08:53
  • @Edem, then u will get the print value as nil or empty because viewedload function in view controller is not called in app delegate, its too early that value is nil. it should be var strName = "Tom", not in viewdidload in view controller to print in app delegate. – AzeTech Mar 25 '19 at 09:00