Last active
December 7, 2015 11:59
-
-
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
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
// | |
// 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