Search code examples
iosobjective-cnsurlsessionnsurlprotocol

A custom NSURLProtocol doesn't invoke canInitWithRequest:


I've implemented a subclass of NSURLProtocol. I need it to mock URL responses for a unit test. I've registered my class in the setUp method of the unit test.

- (void)setUp
{
    [NSURLProtocol registerClass:[RDMockResponseURLProtocol class]];

    [DSMockResponseURLProtocol.mockResponses setObject:[self bigFileResponse]
                                                forKey:[self bigFileURL]];

    <...>
}

I've overridden the class method canInitWithRequest: of NSURLProtocol and its other methods required to be overridden.

@implementation DSMockResponseURLProtocol

<...>

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    return [DSMockResponseURLProtocol.mockResponses.allKeys containsObject:request.URL];
}

Unfortunately canInitWithRequest: isn't being invoked.

I use NSURLSession configured to continue tasks in the background mode. Isn't it causing the issue?

sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];

Please share with me any ideas you have! Thanks in advance [Bow]


Solution

  • It seems like I have found the answer in the documentation.

    You cannot use custom URLProtocol subclasses in conjunction with background sessions.

    https://developer.apple.com/documentation/foundation/urlsessionconfiguration/1411050-protocolclasses