0

While playing with NSURLProtocol, I found [NSURLProtocol propertyForKey:inRequest:] always return nil in stopLoading, but work well for canInitWithRequest:

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    if ([NSURLProtocol propertyForKey:@"URLProtocolHandledKey" inRequest:request]) {
        return NO;
    }

    return YES;
}
- (void)startLoading
{
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:@"URLProtocolHandledKey" inRequest:newRequest];
}

- (void)stopLoading
{
    if ([NSURLProtocol propertyForKey:@"URLProtocolHandledKey" inRequest:self.request]) {
        NSLog(@"Logging");
    }
}

Anything wrong with my code?

keywind
  • 1,135
  • 14
  • 24

1 Answers1

1
NSMutableURLRequest *newRequest = [self.request mutableCopy];

You're creating new object here and setting it's property and you're expecting that property in other instance, that's not the right way.

Make your self.request as NSMutableURLRequest` so that you can directly pass it. e.g.

[NSURLProtocol setProperty:@YES forKey:@"URLProtocolHandledKey" inRequest:self.request];
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184