Display the iOS Network Activity Indicator (Swift)
It’s very easy if you just want to display or hidden the indicator. This code will solve that.
UIApplication.shared.isNetworkActivityIndicatorVisible = true/false
But allways has multiple requests at your apps. Then how can we know when need display or hidden it. So, here it is. We can create a managing class to hold it. The idea is you just need call when a request start/stop, then the managing class will count and display/hidden the indicator.
Here is the code:
class NetworkActivityIndicatorManager: NSObject {
public static let shared = NetworkActivityIndicatorManager()
// MARK: - Property
private var count: Int = 0
private let application = UIApplication.shared
// MARK: - Lifecycle
private override init() { }
// MARK: - Public Methods
public func startActivity() {
DispatchQueue(label: "com.ilukes.naim").sync {
if self.application.isStatusBarHidden {
return
}
if !self.application.isNetworkActivityIndicatorVisible {
self.application.isNetworkActivityIndicatorVisible = true
self.count = 0
}
self.count += 1
}
}
public func stopActivity() {
DispatchQueue(label: "com.ilukes.naim").sync {
if self.application.isStatusBarHidden {
return
}
self.count -= 1
if self.count <= 0 {
self.application.isNetworkActivityIndicatorVisible = false
self.count = 0
}
}
}
}