Skip to content

Instantly share code, notes, and snippets.

@mac-cain13
Last active December 7, 2015 11:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mac-cain13/ab1b9196c99dcc16e5fe to your computer and use it in GitHub Desktop.
Save mac-cain13/ab1b9196c99dcc16e5fe to your computer and use it in GitHub Desktop.
Swift class to manage the UIApplication.networkActivityIndicatorVisible in an effective and simple way
//
// NetworkActivityIndicatorManager.swift
//
// Created by Mathijs Kadijk on 30-10-14.
// From: https://gist.github.com/ab1b9196c99dcc16e5fe
// License: Public domain
//
@objc
class NetworkActivityIndicatorManager {
private var activityCount: Int
private var activityIndicatorVisibilityTimer: NSTimer?
var isNetworkActivityIndicatorVisible: Bool {
return activityCount > 0
}
init() {
activityCount = 0
}
func increment() {
objc_sync_enter(self)
activityCount++
objc_sync_exit(self)
dispatch_async(dispatch_get_main_queue()) {
self.updateNetworkActivityIndicatorVisibilityDelayed()
}
}
func decrement() {
objc_sync_enter(self)
activityCount = max(activityCount - 1, 0)
objc_sync_exit(self)
dispatch_async(dispatch_get_main_queue()) {
self.updateNetworkActivityIndicatorVisibilityDelayed()
}
}
private func updateNetworkActivityIndicatorVisibilityDelayed() {
// Delay hiding of activity indicator for a short interval, to avoid flickering
if (isNetworkActivityIndicatorVisible) {
dispatch_async(dispatch_get_main_queue()) {
self.updateNetworkActivityIndicatorVisibility()
}
} else {
activityIndicatorVisibilityTimer?.invalidate()
activityIndicatorVisibilityTimer = NSTimer(timeInterval: 0.2, target: self, selector: "updateNetworkActivityIndicatorVisibility", userInfo: nil, repeats: false)
activityIndicatorVisibilityTimer!.tolerance = 0.2
NSRunLoop.mainRunLoop().addTimer(activityIndicatorVisibilityTimer!, forMode: NSRunLoopCommonModes)
}
}
func updateNetworkActivityIndicatorVisibility() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = isNetworkActivityIndicatorVisible
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment