1

I want to call a ViewController's member function in AppDelegate's applicationWillResignActive function. Not sure what is the best way to do so. I tried doing so this way:

let landmark = LandmarkViewController()
landmark.test()

but it somehow doesn't seem right. I'm essentially creating new instance of the controller instead of using the already existent one.

Marinos K
  • 1,779
  • 16
  • 39
  • 1
    This may be a good place to send a notification via the [notification center](https://developer.apple.com/reference/foundation/nsnotificationcenter). That your `LandmarkViewController` can be an observer of. – hola Mar 23 '17 at 10:13
  • Are you using storyboard? if Yes, this is the [answer](http://stackoverflow.com/questions/41136597/create-singleton-of-a-viewcontroller-in-swift-3/41136939#41136939) of what are you looking for :) – Ahmad F Mar 23 '17 at 10:13

4 Answers4

6

I think the best way to achieve what you want is to set an observer for this notification UIApplicationWillResignActiveNotification into your view controller itself.

override func viewDidLoad() {
    super.viewDidLoad()
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appDidResign), name: Notification.Name.UIApplicationWillResignActive, object: nil)
}

func appDidResign() {
    // do your stuff
}

deinit {
    NotificationCenter.default.removeObserver(self) //always remember to remove any observers (you can do this in deinit in this case)
}
tanz
  • 2,557
  • 20
  • 31
0

Yes, your above code will create a new instance. If you want to use an existing instance, then you'd need to get a reference to the existing instance somehow.

How you get the reference would depend on how you have your view controllers set. For example, if your LandmarkViewController is the root view controller, you can get it via your UIWindow, perhaps. Or, when your LandmarkViewController instance is created, you can pass a reference to the view controller to the app delegate. It all depends on how your app is set up.

Fahim
  • 3,466
  • 1
  • 12
  • 18
0

You can get the rootViewController (which your LandmarkViewController is how I understood) from the UIWindow:

if let rootViewController = self.window?.rootViewController as LandmarkViewController {
    rootViewController.test()

}
shallowThought
  • 19,212
  • 9
  • 65
  • 112
0

I think best way is add observer for notification in this class. Some think like this:

class LandmarkViewController: ...
{
   ...
   func viewDidLoad()
   {
      ...
      NotificationCenter.default.addObserver(forName: applicationWillResignActive, object: nil, queue: OperationQueue.main) { (notification) in
           ...
      }
   }
}
Sergey
  • 1,589
  • 9
  • 13