Created
October 11, 2019 05:20
-
-
Save strzempa/ed88d468aa72c11c3340d0336efb0062 to your computer and use it in GitHub Desktop.
A way to observe .willEnterForegroundNotification and .didEnterBackgroundNotification with no potential memory issues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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