4

I use Alamofire for networking in my iOS application. I need to run this app in iOS 7+. I want to indicate network activity in status bar, so I created this struct:

struct ActivityManager {

    static var activitiesCount = 0

    static func addActivity() {
        if activitiesCount == 0 {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        }

        activitiesCount++
    }

    static func removeActivity() {
        if activitiesCount > 0 {
            activitiesCount--

            if activitiesCount == 0 {
                UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            }
        }
    }

}

But I don't know, where to call in code addActivity() and removeActivity() methods. I don't want to write them with every request. I want to, that they will be called automatically with every request.

I tried also use pure NSURLSession and NSURLSessionTask and extend them:

extension NSURLSessionTask {

    func resumeWithActivity() {
        ActivityManager.addAction()
        self.resume()
    }

}


public extension NSURLSession {

    func OwnDataTaskWithRequest(request: NSURLRequest!, ownCompletionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask! {

        return self.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
            ActivityManager.removeAction()
            ownCompletionHandler!(data, response, error)
        })
     }

}

Then I used them like this:

var session: NSURLSession = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)

session.OwnDataTaskWithRequest(request) { (data, response, error) -> Void in
    // some logic here            
}.resumeWithActivity()

But this approach doesn't work. In iOS 7 is NSURLSession extension not visible. I created a bug report for this (with sample project).

Can you please give me some advise, how to reach my goal? With or without Alamofire?

Alexis
  • 16,629
  • 17
  • 62
  • 107
Deny
  • 1,441
  • 1
  • 13
  • 26

1 Answers1

1

If you don't want to call your functions manually for every request and that you want to use Alamofire, I suggest you to improve it to add the network activity indicator feature.

Have a look at the source of Alamofire

You need to register 2 notification observers in your ActivityManager and then trigger the notifications at the relevant places either in Alamofire.Manager or in Alamofire.Request.

Also have a look at the source of AFNetworkActivityIndicatorManager which implement the feature you want in AFNetworking.

Alexis
  • 16,629
  • 17
  • 62
  • 107