在玩NSURLProtocol时,我发现[NSURLProtocol propertyForKey:inRequest:]在stopLoading中总是返回nil,但是对于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");
    }
}


我的代码有问题吗?

最佳答案

NSMutableURLRequest *newRequest = [self.request mutableCopy];


您在这里创建新对象并设置它的属性,并且在其他情况下期望该属性,这不是正确的方法。

将您的self.request设置为NSMutableURLRequest`,以便您可以直接传递它。例如

[NSURLProtocol setProperty:@YES forKey:@"URLProtocolHandledKey" inRequest:self.request];

关于ios - iOS:[NSURLProtocol propertyForKey:inRequest:]返回nil,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23825240/

10-13 04:00