With Swift 4, Apple advises via a new compiler warning that we avoid the use of #selector
in this scenario. The following is a much safer way to accomplish this:
First, create a lazy var that can be used by the notification:
lazy var didBecomeActive: (Notification) -> Void = { [weak self] _ in
// Do stuff
}
If you require the actual notification be included, just replace the _
with notification
.
Next, we set up the notification to observe for the app becoming active.
func setupObserver() {
_ = NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive,
object: nil,
queue:.main,
using: didBecomeActive)
}
The big change here is that instead of calling a #selector
, we now call the var created above. This can eliminate situations where you get invalid selector crashes.
Finally, we remove the observer.
func removeObserver() {
NotificationCenter.default.removeObserver(self, name: .UIApplicationDidBecomeActive, object: nil)
}