KML
KML

Reputation: 2322

Update specific ViewController when it comes into view

I have two UIViewControllers that I would each like to update whenever they come into view.

In DashBordViewControlller I have therefore added this code:

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
    appDelegate.dashboardViewController = self

and in DetailViewController this code:

override func viewDidLoad() {
    super.viewDidLoad()

    let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
    appDelegate.detailViewController = self

In AppDelegate I have added this code:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

var dashboardViewController:DashboardViewController?
var detailViewController:DetailViewController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    return true
}

func applicationWillResignActive(application: UIApplication) {
  }

func applicationDidEnterBackground(application: UIApplication) {
     println("Goodbye world")
}

func applicationWillEnterForeground(application: UIApplication) {
    println("Hello again world")
    dashboardViewController?.cleanCDandQueryHKLoop()
    detailViewController?.rememberWhatSegmentIsPressed()
}

My problem is that both UIViewControllers update whenever either ViewController comes into view. For example if I close the app (Home) and then reopen it.

How can I check in AppDelegate which ViewController is coming into view and only update that one? Any help would be very much appreciated - thank you !

Upvotes: 0

Views: 48

Answers (1)

Dani
Dani

Reputation: 1288

You should add an observer in your view controller's viewWillAppear like this:

override func viewWillAppear(animated: Bool) {
  super.viewWillAppear(animated)
  NSNotificationCenter.defaultCenter().addObserver(self, selector: "willEnterForeground:", name: UIApplicationWillEnterForegroundNotification, object: nil)
}

After that, implement your function:

func willEnterForeground(notification: NSNotification!) {
  // View Controller is brought to Foreground
}

Oh, and don't forget to remove the observer on viewWillDisappear:

override func viewWillDisappear(animated: Bool) {
  super.viewWillDisappear(animated)
  NSNotificationCenter.defaultCenter().removeObserver(self, name: nil, object: nil)
}

Upvotes: 1

Related Questions