ios - 缓存不适用于自定义 NSURLProtocol

标签 ios objective-c nsurlconnection nsurlprotocol

我正在尝试创建 NSURLProtocol 的子类。但是,我注意到当我注册我的子类时我似乎失去了缓存功能,即使它不应该做任何事情。例如,如果我对同一个 URL 多次执行 [NSURLConnection sendSynchronousRequest...] 而没有注册子类,它只会执行一个实际的 http 请求。注册该子类后,每次都会进行一次网络请求。

这是我的代码:

@interface CustomURLProtocol : NSURLProtocol
@property (nonatomic, strong) NSURLConnection *connection;
@end

@implementation CustomURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    return [[[request URL] scheme] isEqualToString:@"http"] &&
           [NSURLProtocol propertyForKey:@"tagged" inRequest:request] == nil;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

- (void)startLoading {
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:@"tagged" inRequest:newRequest];
    self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];
}

- (void)stopLoading {
    [self.connection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [[self client] URLProtocol:self didLoadData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [[self client] URLProtocol:self didFailWithError:error];
    self.connection = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:[[self request] cachePolicy]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection  {
    [[self client] URLProtocolDidFinishLoading:self];
    self.connection = nil;
}
@end

最佳答案

这里的问题不是我所期望的。真正的问题是重定向没有被正确处理,因为下面的代码不存在:

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
  [[self client] URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
  return request;
}

如果没有这段代码,重定向将不会被缓存,因此对重定向 URL(如 wikipedia.com)的连续请求每次都会导致重定向。

关于ios - 缓存不适用于自定义 NSURLProtocol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19062186/

相关文章:

ios - 创建临时 CoreData 实体(在非持久性 MagicalRecord 上下文中)?

iphone - iPhone 上的 Instagram 图像过滤器

objective-c - (异步)NSURLConnection : what's going on underneath?

iphone - 在 Controller 之间传递 UISegmentedControl 值...

ios - 我们如何在使用 Eureka 单击单元格后执行条件

objective-c - 在 ARC ObjectiveC++ 中使用 C++11 lambda 函数——如何正确使用?

ios - 在 NSThread 或 NSOperation 中使用 NSUrlConnection

iphone - 2D 和 3D 变换可以应用于 iOS 控件吗?

iphone - iOS 某些八进制转义序列导致 stringWithUTF8String 为 nil

objective-c - 缓存流视频