0

I have tried to use NSURLProtocol to log all requests in a Swift 2.3 project. However not all URL requests are being logged. Specifically all the Alamofire requests are not being recorded.

Sample code

class AppDelegate: NSObject, NSApplicationDelegate{
    func applicationDidFinishLaunching(aNotification: NSNotification) {
        NSURLProtocol.registerClass(TestURLProtocol)
        Alamofire.request(.GET, SomeURL).responseSwiftyJSON({ (request, response, json, error) in })
    }
}

class TestURLProtocol: NSURLProtocol {
    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        print("request \(request.URL!)") // never called
        return false
    }
}
datinc
  • 3,404
  • 3
  • 24
  • 33

2 Answers2

0

I think this is because Alamofire uses the new URLSession API, which is not affected by the NSURLProtocol.registerProtocol call.

You have to create a URLSession with URLSessionConfiguration that has its protocolClasses array set to [TestURLProtocol.self].

But with this you would have to use a custom SessionManager everywhere to log the requests, instead of using the implicit Alamofire.request I think.

Alistra
  • 5,177
  • 2
  • 30
  • 42
  • I have tried to use the method from this response and it did not work. http://stackoverflow.com/a/28720198/1449607 – datinc Feb 10 '17 at 18:54
  • Yeah, but you have to inject the configuration in the session manager and then use that instead of `Alamofire.request` – Alistra Feb 10 '17 at 18:55
  • I am trying to also monitor third party services. I am looking for a solution that will let me monitor those requests without modifications of their code. – datinc Feb 10 '17 at 18:57
0

What I ended up using was the pod OHHTTPStubs. I added the following code to my app delegate to log every host being used.

func applicationDidFinishLaunching(aNotification: NSNotification) {
    var hosts = [String: Int]()

    stub({ req in
        if let url = req.URL, let host = url.host{
            var count = 1
            if let c = hosts[host]{
                count = c + 1
            }
            hosts[host] = count

            print("Request #\(count): Host = \(host)")
        }
        return false
        },
         response:{_ in return OHHTTPStubsResponse()}
    );
}
datinc
  • 3,404
  • 3
  • 24
  • 33