11

I'm working with Alamofire. Following up on Mattt's comment in one of the closed issues on GitHub, I attempted a NSURLProtocol-based mechanism to set the UIApplication.sharedApplication().networkActivityIndicatorVisible flag.

However, after registering my custom protocol with Alamofire's underlying NSURLSessionConfiguration I got stuck pretty quickly since Alamofire doesn't expose much of its SessionDelegate class.

Is there a simple way to notify the custom NSURLProtocol the request has completed without reproducing much of the already existing implementation of Alamofire inside my NSURLProtocol?

mokagio
  • 16,391
  • 3
  • 51
  • 58
opfeffer
  • 603
  • 5
  • 19

1 Answers1

0

A different way of doing it (not implementing NSURLProtocol-way) would be creating an API which would have an executeRequest method:

func executeRequest(method: Alamofire.Method, url: NSURL, parameters: [String: String]?, headers: [String : String]?) {
        // Show activity indicator on status bar
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true

        let request = manager.request(method, url, parameters: parameters, encoding: .JSON, headers: headers)
            .responseJSON {
                response in
                ...

                // Hide activity indicator on status bar
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    }

Of course, all your requests would have to be executed using the newly created API.

GicaGG
  • 56
  • 7
  • But this breaks as soon as you have two concurrent requests, right? – Victor Jalencas May 11 '16 at 11:17
  • Yes indeed. Having two requests, if one of them finishes earlier, the activity indicator will hide before the second request finishes too. But this can be easily fixed. You can keep count of active requests, and hide the activity indicator only when active requests count is 0. – GicaGG May 11 '16 at 13:02