Skip to content

Instantly share code, notes, and snippets.

@strzempa
Created October 11, 2019 05:20
Show Gist options
  • Save strzempa/ed88d468aa72c11c3340d0336efb0062 to your computer and use it in GitHub Desktop.
Save strzempa/ed88d468aa72c11c3340d0336efb0062 to your computer and use it in GitHub Desktop.
A way to observe .willEnterForegroundNotification and .didEnterBackgroundNotification with no potential memory issues
import UIKit
public protocol EnterForegroundObservable: AnyObject {
var applicationWillEnterForegroundObservation: Any? { get set }
typealias ForegroundBackgroundObservationCompletionHandler = () -> Void
func applicationWillEnterForegroundObservation(completion: ForegroundBackgroundObservationCompletionHandler?)
}
public extension EnterForegroundObservable {
func applicationWillEnterForegroundObservation(completion: ForegroundBackgroundObservationCompletionHandler?) {
applicationWillEnterForegroundObservation = NotificationCenter.default.addObserver(
forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in
completion?()
}
}
}
public protocol EnterBackgroundObservable: AnyObject {
var applicationDidEnterBackgroundObservation: Any? { get set }
typealias ForegroundBackgroundObservationCompletionHandler = () -> Void
func applicationDidEnterBackgroundObservation(completion: ForegroundBackgroundObservationCompletionHandler?)
}
public extension EnterBackgroundObservable {
func applicationDidEnterBackgroundObservation(completion: ForegroundBackgroundObservationCompletionHandler?) {
applicationDidEnterBackgroundObservation = NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { _ in
completion?()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment