我们必须实施:
+ (BOOL)canInitWithRequest:(NSURLRequest *)request + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request - (void)startLoading - (void)stopLoading
canInitWithRequest很简单,这就是告诉NSURLProtocol您将响应此请求的方式.
我不知道如何处理canonicalRequestForRequest:
在startLoading:中,我要么从本地文件创建响应,要么同步获取远程文件,然后调用客户端方法:
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; [self.client URLProtocol:self didLoadData:responseData]; [self.client URLProtocolDidFinishLoading:self];
- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
当我决定从远程服务器获取资源时(当它尚未缓存时).
最后,我还没弄清楚如何处理stopLoading:
如果有人知道这些方法应该做的更多,那么您的见解将非常受欢迎.
解决方法
“It is up to each concrete protocol implementation to define what
“canonical” means. A protocol should guarantee that the same input
request always yields the same canonical form.Special consideration should be given when implementing this method,
because the canonical form of a request is used to lookup objects in
the URL cache,a process which performs equality checks between
NSURLRequest objects.”
它只是说:
Make sure that two requests that are EFFECTIVELY the same URL … end up using EXACTLY the same request-string
…如果可用的话,请求一个将返回另一个的预缓存版本.
您应该可以再次返回请求.您可以通过检查不需要URL编码但是(例如,如果有文字破折号/连字符编码)的字符来对其进行处理.
wasRedirectedToRequest – 来自文档(https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSURLProtocolClient_Protocol/Reference/Reference.html)
“Sent to indicate to the URL loading system that the protocol
implementation has been redirected. (required)”
即,如果请求通过HTTP重定向代码(例如30x状态代码)重定向,则只能调用此方法.
注意:在STACKOVERFLOW中的错误意味着我无法输入我想要的内容
例如,服务器可能会将“http:// server”重定向到“http:// server / index.html” – 并且此回调允许您通知接收方它将从稍微不同的URL获取响应它要求.
同样,这对于正确的缓存等是必要的.