fyxrhyry
fyxrhyry

Reputation: 135

NSURLSession sessionWithConfiguration did not call in custom NSURLProtocol's method canInitWithRequest

I have a subclass of NSURLProtocol, The NSURLConnection works well.

And [NSURLSession sharedSession] works well too.

But, [NSURLSession sessionWithConfiguration:configuration] not work,

I called the [NSURLProtocol registerClass:NSURLProtocolSubclass.class];

what's error?

NSString * stringUrl = @"https://www.apple.com/";
NSURL * url = [NSURL URLWithString:stringUrl];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
urlRequest.HTTPMethod = @"GET";

NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.timeoutIntervalForResource = 20.0;

//this can work, but I cann't edit.
//configuration.protocolClasses = @[NSURLProtocolSubclass.class];

//this can work.
NSURLSession * urlSession = [NSURLSession sharedSession];

//this not work.
//NSURLSession * urlSession = [NSURLSession sessionWithConfiguration:configuration];

//Task.
NSURLSessionDataTask * task = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSHTTPURLResponse * httpUrlResponse = (NSHTTPURLResponse *)response;
    NSLog(@"---- session: %ld", (long)httpUrlResponse.statusCode);
}];
[task resume];

Upvotes: 1

Views: 974

Answers (1)

dgatwood
dgatwood

Reputation: 10407

The registerClass method registers a protocol with NSURLConnection and with the shared session only. Other sessions copy the global set of protocols at the time the session is created, IIRC, unless you provide a custom array, in which case it copies that array.

Ether way, if you need to add protocols while your app is running, I'm pretty sure you have to create a new session each time unless you use the shared session.

Upvotes: 7

Related Questions