The canInitWithRequest method in the NSURLProtocol custom class does not start when using Alamofire

I have a custom NSURLProtocol class to provide test data while I'm experimenting with Alamofire, but it doesn't seem to be used when querying through the Manager's request method.

This request passes and returns the result just fine, but does not call canInitWithRequest:

NSURLProtocol.registerClass(DBDummyURLProtocol) class MyURLRequestConvertible : URLRequestConvertible { var URLRequest: NSURLRequest { return NSURLRequest(URL: NSURL(scheme: "http", host: "cnn.com", path: "/")!) } } var myURLRequestConvertible = MyURLRequestConvertible(); Manager.sharedInstance.request(myURLRequestConvertible) 

If I use a simple NSURLConnection, the canInitWithRequest method is called as I expected:

  NSURLProtocol.registerClass(DBDummyURLProtocol) var request = NSURLRequest(URL: NSURL(scheme: "http", host: "cnn.com", path: "/")!) NSURLConnection(request: request, delegate:nil, startImmediately:true) 

Am I doing something wrong? Should this work with Alamofire?

+8
alamofire
source share
1 answer

Alamofire uses NSURLSession internally, which does not take into account protocol classes registered with NSURLProtocol.registerClass() . Instead, it uses the NSURLSessionConfiguration object, which has the protocolClasses property.

Unfortunately, this configuration cannot be changed since the session always returns a copy and the property is not writable.

Instead, you can create your own instance of Alamofire.Manager and pass the custom NSURLSessionConfiguration

 let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.protocolClasses.insert(DBDummyURLProtocol.self, atIndex: 0) let manager = Manager(configuration: configuration) manager.request(.GET, "http://example.com") 
+16
source share

All Articles