gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:55:06 25 4
gpt4 key购买 nike

我正在尝试创建 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com