public class Spinner {
private var scene: UIWindowScene? {
UIApplication
.shared
.connectedScenes
.first as? UIWindowScene
}
private var root: UIViewController? {
scene?
.keyWindow?
.rootViewController
}
private var activityIndicator: UIActivityIndicatorView?
@MainActor public func start(
_ style: UIActivityIndicatorView.Style = .medium,
color: UIColor = .gray
) {
if self.activityIndicator == nil {
let indicator = UIActivityIndicatorView()
indicator.style = style
indicator.color = color
indicator.hidesWhenStopped = true
indicator.frame = .init(
x: 0, y: 0, width: 50, height: 50
)
self.activityIndicator = indicator
root?.view.addSubview(indicator)
indicator.center = root?.view.center ?? .init()
}
activityIndicator?.startAnimating()
}
@MainActor public func stop() {
self.activityIndicator?.stopAnimating()
}
}
public struct SpinnerKey: EnvironmentKey {
public static var defaultValue = Spinner()
}
public extension EnvironmentValues {
var spinner: Spinner {
self[SpinnerKey.self]
}
}