Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canInitWithRequest method in custom NSURLProtocol class is not triggered when using Alamofire

Tags:

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 making requests via the Manager request method.

This request goes through and returns a result just fine, but does not trigger 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?

like image 962
Doug Sjoquist Avatar asked Oct 23 '14 00:10

Doug Sjoquist


1 Answers

Alamofire uses NSURLSession internally which does not respect the protocol classes registered using NSURLProtocol.registerClass(). Instead it uses a NSURLSessionConfiguration object which has a protocolClasses property.

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

What you can do instead is create your own instance of Alamofire.Manager and pass it a custom NSURLSessionConfiguration

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.protocolClasses.insert(DBDummyURLProtocol.self, atIndex: 0)
let manager = Manager(configuration: configuration)

manager.request(.GET, "http://example.com")
like image 97
Alfonso Avatar answered Oct 23 '22 18:10

Alfonso