9

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?

Doug Sjoquist
  • 735
  • 5
  • 9

1 Answers1

19

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")
Alfonso
  • 8,386
  • 1
  • 43
  • 63
  • 2
    Worth clarifying that `NSURLSession.shared` does absolutely respect protocol classes registered using `registerClass(_:)` however, sessions created using any initializer methods (i.e. not the shared session) do not. The latter is what Alamofire uses, and that's why it ignores `registerClass(_:)`. – paulvs Aug 07 '17 at 02:45
  • I'm was trying to find out how this was done as well and how [OHHTTPStubs](https://github.com/AliSoftware/OHHTTPStubs) supports Alamofire without needing control over the `NSURLSessionConfiguration`. Turns out, OHHTTPStubs does the same thing, via [method siwzzling](https://github.com/AliSoftware/OHHTTPStubs/blob/826a9217fcd468220d154ed0075cbc1a20d0c5c9/OHHTTPStubs/Sources/NSURLSession/OHHTTPStubs%2BNSURLSessionConfiguration.m). – nteissler Nov 20 '19 at 04:05