NSURLSession sessionWithConfiguration没有在自定义NSURLProtocol的方法canInitWithRequest中调用

fyx*_*yry 1 nsurlprotocol nsurlsession

我有一个NSURLProtocol的子类,NSURLConnection运作良好。

并且[NSURLSession sharedSession]也很好用。

但是,[NSURLSession sessionWithConfiguration:configuration]不起作用,

我叫[NSURLProtocol registerClass:NSURLProtocolSubclass.class];

怎么了

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];
Run Code Online (Sandbox Code Playgroud)

dga*_*ood 6

registerClass方法在NSURLConnection和共享会话中注册协议。其他会话将在创建会话时复制全局协议集IIRC,除非您提供自定义数组,在这种情况下,它将复制该数组。

以其他方式,如果您需要在应用运行时添加协议,我敢肯定您每次都必须创建一个新会话,除非您使用共享会话。