The app has an animation that stops when the app goes into background or foreground, and restarts when the app gets active again.

How can I do this without using observers? I read in other threads that this way is not a good practice and the app can crash.

override func viewDidLoad() {
    super.viewDidLoad()

    myView.startAnimations()

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willEnterForegroundNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

}


override func viewWillAppear(_ animated: Bool) {
    myView.startAnimations()
}
override func viewDidDisappear(_ animated: Bool) {
    myView.stopAnimations()
}

@objc func appMovedToBackground() {
    myView.stopAnimations()
}

@objc func appMovedToForeground() {
    myView.stopAnimations()
}

@objc func appBecomeActive() {
    myView.startAnimations()
}

1 Answers

0
Gonzalo DuraƱona On

If you seek for stability and compatibility with older iOS versions, I would recommend KVObserver https://github.com/postmates/PMKVObserver, it helps maintaining the observer count, helping with the requirement to remove the observer when the observed object is going to be released for iOS 10 and below.

Your code is perfectly fine as it is, just fix the selector for UIApplication.willEnterForegroundNotification