4

I'm trying to change a Label's text or show an alert when my iOS app becomes active from the background state.

When I call a function in the ViewController class only the print() method works fine. But when I want to interact with the objects in that class, it shows errors.

SceneDelegate.swift:

var vc = ViewController()

func sceneDidBecomeActive(_ scene: UIScene) {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.

    vc.showMessage("Test message")
}

ViewController.swift:

@IBOutlet weak var textLabel: UILabel!

func showMessage(_ incomingMessage:String!) {
    let warning = UIAlertController(title: "Warning", message: incomingMessage, preferredStyle: .alert)
    let aButton = UIAlertAction(title: "OK", style: .cancel, handler: nil)
    warning.addAction(aButton)

    self.present(warning, animated: true)

    textLabel.text = incomingMessage

    print("message is : " + incomingMessage)
}

1 Answer 1

6

As always, the proper solution is to have the view controller listen for the corresponding lifecycle event instead of having the app delegate or scene delegate attempt to tell the view controller anything.

In your scene delegate, remove the creation of ViewController and the attempt to call showMessage.

Then update your ViewController class. Add the following to viewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(didActivate), name: UIScene.didActivateNotification, object: nil)

Then add the didActivate method:

func didActivate() {
    showMessage("Test Message")
}

And then add deinit:

deinit {
    NotificationCenter.default.removeObserver(self)
}

This way only the view controller needs to know the logic of what it needs to do and when.

Also note that if you really want to detect when the scene returns from the background (enters the foreground), then use the willEnterForegroundNotification notification instead of didActivateNotification.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.