NSURLProtocol doesn't get complete NSURLRequest

Problem : I have my subclass of NSURLProtocol, but the NSURLRequest returned by +canonicalRequestForRequest: or the request returned by -connection:willSendRequest:redirectResponse: are never passed to my URL protocol instance.

Details : In my subclass of NSURLProtocol , I implement the method +canonicalRequestForRequest: to add an HTTP header to the request. The header is added successfully, but when -startLoading is called on my URL protocol, self.request doesn't include that header.

Additionally, when connection:willSendRequest:redirectResponse: is called on the delegate of the NSURLConnection , whatever request is returned by that method never reaches my URL protocol instance either.

I think the problem lies in that initWithRequest:cachedResponse:client: is called before +canonicalRequestForRequest: or connection:willSendRequest:redirectResponse: are called, and the resulting requests from those 2 methods are never passed to my URL protocol instance after it has been alloc / init .

Is this a bug in Apple's URL loading system? Is there a workaround? Am I doing something wrong?


Update on April 6, 2014

Here is some sample code. I set 2 headers: one in -[APViewController connection:willSendRequest:redirectResponse:] called X-WillSendRequestTest and the other one in +[APURLProtocol canonicalRequestForRequest:] . Neither one is in the NSURLRequest fetched by calling self.request within -[APURLProtocol startLoading] .

APViewController.m (the delegate of NSURLProtocol)

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse {
    NSLog(@"Will send request: %@", request);

    NSMutableURLRequest *newRequest = [request mutableCopy];

    // This header will not be in self.request when fetched within the -[APURLProtocol start loading] method.
    [newRequest setValue:@"12345" forHTTPHeaderField:@"X-WillSendRequestTest"];

    NSLog(@"New request: %@", newRequest);

    return newRequest;
}

APURLProtocol.m

@interface APURLProtocol () <NSURLConnectionDelegate, NSURLConnectionDataDelegate>
// Private properties
@property (nonatomic, strong) NSURLConnection *connection;
@end




@implementation APURLProtocol

#pragma mark -
#pragma mark Init methods

- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client {
    NSLog(@"%@", NSStringFromSelector(_cmd));

    if ((self = [super initWithRequest:request cachedResponse:cachedResponse client:client])) {

    }

    return self;
}



#pragma mark -
#pragma mark dealloc

- (void)dealloc {
    NSLog(@"%@", NSStringFromSelector(_cmd));

    [_connection cancel];
}



#pragma mark -
#pragma mark Inherited class methods

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    NSLog(@"%@ %@", NSStringFromSelector(_cmd), request);

    id requestIsHandled = [self propertyForKey:kAPURLProtocolHandledRequest inRequest:request];

    if (requestIsHandled == nil
            && ([request.URL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame
                    || [request.URL.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame
                    || [request.URL.scheme caseInsensitiveCompare:@"ftp"] == NSOrderedSame)) {
                NSLog(@"YES");
                return YES;
            }

    NSLog(@"NO");
    return NO;
}


+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    NSLog(@"%@", NSStringFromSelector(_cmd));

    NSMutableURLRequest *newRequest = [request mutableCopy];
    // This header will not be in self.request when fetched within the -[APURLProtocol start loading] method.
    [newRequest setValue:@"12345" forHTTPHeaderField:@"X-CanonicalRequestTest"];

    return newRequest;
}


+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)aRequest toRequest:(NSURLRequest *)bRequest {
    NSLog(@"Request is cache equivalent:");
    NSLog(@"Request 1: %@", aRequest);
    NSLog(@"Request 2: %@", bRequest);

    return YES;
}



#pragma mark -
#pragma mark Inherited instance methods

- (void)startLoading {
    NSLog(@"%@. Request: %@", NSStringFromSelector(_cmd), self.request);

    NSMutableURLRequest *newRequest = [[self request] mutableCopy];
    [[self class] setProperty:@"" forKey:kAPURLProtocolHandledRequest inRequest:newRequest];

    [self.connection cancel];

    self.connection = [[NSURLConnection alloc] initWithRequest:newRequest
                                                                                                        delegate:self
                                                                                        startImmediately:YES];
}
@end

NSURLRequest+test.m (category to extend the description of NSURLRequest)

Warning : Do not do this at home. Do not override a method or property using categories. This is for quick debugging purposes only.

@implementation NSURLRequest (test)

- (NSString *)description {
    NSString *dataString = [[NSString alloc] initWithData:self.HTTPBody encoding:NSUTF8StringEncoding];

    return [NSString stringWithFormat:@"%@: %p {URL: %@, Method: %@, Headers: %@, Data: %@",
                    NSStringFromClass([self class]), self, self.URL, self.HTTPMethod, [self allHTTPHeaderFields], dataString];
}

@end
链接地址: http://www.djcxy.com/p/34838.html

上一篇: 使用AFNetworking与自定义NSURLProtocol类

下一篇: NSURLProtocol没有完成NSURLRequest