Jared L.
Jared L.

Reputation: 207

How to use applicationWillResignActive to call a function of a view controller

I am trying to call my menu view inside my view controller when the home button is pressed, or for that matter when the user gets a phone call, etc...

My goal is to call the function: toggleMenu() that is inside the QuestionViewController. Here's the code:

class QuestionViewController: UIViewController, MFMailComposeViewControllerDelegate {

///////////

    func toggleMenu() {

    // Show or hide menu

    if menuStackView.isHidden == true {

        // Show the menu
        print("Showing Menu")
        // Update labels
        questionNumberMenuLabel.text = questionNumberLabel.text
        endTimer()
        menuStackView.isHidden = false
        animateInMenu()


    } else {

        // Hide the menu
        animateOutMenu()

    }
}

I do believe I should utilize the following method found in the AppDelegate.swift file:

    func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

If I'm on the right track I need help calling the toggleMenu() function of the QuestionViewController class in this method. How do I do that?

Thanks so much!

Upvotes: 0

Views: 2206

Answers (1)

Duncan C
Duncan C

Reputation: 131501

Use the NotificationCenter and listen for UIApplicationWillResignActiveNotification. The system broadcasts that notification as well as calling your app delegate's applicationWillResignActive method (assuming you have one.)

Listen for notifications (using the method addObserver(forName:object:queue:using:) in your viewDidLoad. If you don't need to support iOS versions < 9.0, you don't need to worry about calling removeObserver - the system takes care of it for you.

Upvotes: 1

Related Questions