sarah
sarah

Reputation: 1221

viewWillAppear is not being called after clicking the home button

i have this view controller

class ViewController: UIViewController {


 override func viewWillAppear(animated: Bool) {
        let user = NSUserDefaults()
        let mobileNumber = user.valueForKey("mobileNumber") as? String
        if let mobileNumber = mobileNumber {
            print("mobile number = \(mobileNumber)")
        }else {
            print("no mobile number")
        }
    }


    @IBAction func makePhoneCall(sender: UIButton) {
 if let phoneCall = phoneCall {
            let user = NSUserDefaults()
            user.setValue(phoneCall, forKey: "mobileNumber")

when the user clicks on a button, i save the mobileNumber in nsuserdefault.

then i click the button, then i open the app again, but problem is that when i open the app agian, i don't bet any message from the viewWillAppear even though i am printing in the if and in the else part.

Upvotes: 3

Views: 637

Answers (2)

Brian Nickel
Brian Nickel

Reputation: 27560

tylersimko is correct that viewWillAppear(_:) is not called when the application enters the foreground and that event is instead captured by "application will enter background".

That said, you don't need to observe this from the app delegate but could instead use the UIApplicationWillEnterForegroundNotification notification:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

func applicationDidEnterForeground() {
    // Update variable here.
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

The above code:

  1. When your view loads, your view controller registers to have the function applicationDidEnterForeground() called whenever the application enters the foreground.
  2. The function applicationDidEnterForeground() does whatever needs to be done.
  3. The view controller unregisters from all notifications when it deallocates to avoid a zombie reference in iOS versions before 9.0.

Given that you are working with NSUserDefaults, you could instead consider observing NSUserDefaultsDidChangeNotification.

Upvotes: 3

tylersimko
tylersimko

Reputation: 313

In AppDelegate.swift, make your change in applicationWillEnterForeground:

func applicationWillEnterForeground(application: UIApplication) {
    // do something
}

Alternatively, if you want to keep your changes in the ViewController, you could set up a function and call it like this:

func applicationWillEnterForeground(application: UIApplication) {
    ViewController.refreshView()
}

Upvotes: 2

Related Questions