• Swift Development – Managing the Network Activity Indicator

    On iOS devices there is a little spinner on the status bar which can be used to communicate to the user that some form of network access is underway. Making use of this feature is as simple as:

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    The problem comes if you have an app which has a number of asynchronous tasks which may run simultaneously and finish in any order. In this scenario, it is possible that one task might cancel the indicator whilst another is yet to complete.

    The solution to this problem is to define a single function which keeps track of the number of times the network activity indicator has been enabled or disabled. This function should live somewhere where all view controllers can have access to it – the ideal place is probably your AppDelegate:

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
        var activityIndicatorSetVisibleCount = 0
    
        ...
        
        func setNetworkActivityIndicatorVisible(visible: Bool) {
            if visible {
                ++activityIndicatorSetVisibleCount
            }else {
                --activityIndicatorSetVisibleCount
            }
            
            // If you have more closes than opens, make sure not to enter into minus numbers
            if activityIndicatorSetVisibleCount < 0 {
                 activityIndicatorSetVisibleCount = 0
             }
             UIApplication.sharedApplication().networkActivityIndicatorVisible = activityIndicatorSetVisibleCount > 0
        }
    

    Then, where you want to call this, you would do:

    (UIApplication.sharedApplication().delegate as AppDelegate).setNetworkActivityIndicatorVisible(true)

One Responseso far.

  1. Oleg says:

    Thank You!

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you human: *