iosswiftviewdidappear

ViewDidAppear not executed every time app comes to foreground


Im building an IoT app using Arduino board and calling an API to check the updated pin values of the Arduino board.

When i receive the update from the API i have to update my button colors to red or green according to the data i'm receiving. First time i load the app it works just fine and the viewDidAppear() is called. But when i go to the background then to the foreground again it is not called. What i know is that every time view appears it has to run the instructions inside of the function but seems like that is not the case.

I tried to put my code in the AppDelagate applicationDidBecomeActive() but because i'm trying to update my views and the view is not there yet it gives me fatal error found nil. Here are my instructions in the viewDidAppear()

    override func viewDidAppear(_ animated: Bool) {

    activityIndicator.startAnimating()

    definingPinModes(pin: [7,6,5,4], mode: 1)

    getAllInputValues(key: key, method: .post) { (status, newValues, msg) in

        if status == 200 {
            //Change button colors according to values in array
            self.changeButtonColors(values: newValues!)

        } else {

            print("Error getting pin values")

            self.alertMessage(title: "Connection Error", message: "Failed retrieving pin values")
            return
        }
        self.activityIndicator.stopAnimating()
    }

}

Solution

  • In addition to viewDidAppear, you can have your view controller observe UIApplication.didBecomeActiveNotification (previously known as UIApplicationDidBecomeActive):

    private var observer: NSObjectProtocol?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        observer = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] notification in
            self?.updateUI()
        }
    }
    
    deinit {
        if let observer = observer {
            NotificationCenter.default.removeObserver(observer)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        updateUI()
    }
    
    private func updateUI() {
        // do your UI update stuff here
    }