Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method in view controller in app delegate?

Tags:

ios

swift

I need to call a method in my ViewController class in AppDelegate. This is what the method looks like this:

class ViewController: UIViewController {

    func myFunction() {
        ...
    }
}

I've tried using window.rootViewController, but it's telling me the method myFunction does not exist, since rootViewController is of type UIViewController.

I've also tried

var vc = ViewController()
self.vc.myFunction()

But this is creating a new instance of the ViewController class, and that's not what I want, either.

Here is the part of the AppDelegate code that I need myFunction to be called from:

class AppDelegate: UIResponder, UIApplicationDelegate {

    func handleEvent() {
        if UIApplication.shared.applicationState == .active {
            // call myFunction()
        }
        else {
            ...
        }
    }
}

Context: I'm following a geofencing tutorial: https://www.raywenderlich.com/136165/core-location-geofencing-tutorial

Since user location is being monitored even when app is closed, when an event is triggered, AppDelegate should be used to handle the event, since view controller is not yet loaded.

In my AppDelegate that handles event, if the application is active, I would like to pop up an alert to have the user choose to stop monitoring location. The function that stops location monitoring (myFunction) is in view controller.

like image 995
Asteria Avatar asked Apr 22 '17 23:04

Asteria


2 Answers

if its the root its easy:

(window.rootViewController as? ViewController)?.myFunction()

if its on top of a navigationController

((window.rootViewController as? UINavigationController)?.topViewController as? ViewController)?.myFunction()

But in either case its weird and probably not the right thing to do. Use NotificationCenter instead and post a notification name in your AppDelegate and then have the ViewController listen for messages and respond accordingly.

like image 128
Josh Homann Avatar answered Sep 20 '22 10:09

Josh Homann


You shouldn't call view controllers methods from the appdelegate. Is a bad practice and generally is not required. If you want to react to methods such as: willResignActive willTerminate

you should listen to notifications for those events using the NotificationCenter.

like image 20
dmlebron Avatar answered Sep 20 '22 10:09

dmlebron