ios – NSURLProtocol的抽象方法

我一直在我的应用程序中使用自定义NSURLProtocol来检测资源并从缓存目录加载(如果可用),或重定向回我的应用程序的服务器.但是,我发现缺少抽象方法的文档,我不知道如何处理我们需要实现的一些抽象方法.

我们必须实施:

+ (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:

如果有人知道这些方法应该做的更多,那么您的见解将非常受欢迎.

解决方法

canonicalRequestForRequest – 来自文档( https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLProtocol_Class/Reference/Reference.html)

“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获取响应它要求.

同样,这对于正确的缓存等是必要的.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...