我有一个使用自定义NSURLProtocol的应用程序想要拦截http请求和响应与本地数据。但它只能在某些时候起作用。 这是两个重要的功能:
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
NSString *flag=[NSURLProtocol propertyForKey:CachingURLHeaderKey inRequest:request];
if (flag==nil ) {
return YES;
}
return NO;
}
- (void)startLoading
{
NSMutableURLRequest *proxyRequest = [self.request mutableCopy];
[NSURLProtocol setProperty:@"done" forKey:CachingURLHeaderKey inRequest:proxyRequest];
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *ResourceCacheDir = [resourcePath stringByAppendingPathComponent:[@"cache/" stringByAppendingString:MyFileKey]];
NSData *ReturnData=[NSData dataWithContentsOfFile:ResourceCacheDir];
if (ReturnData!=nil) {
headers = [NSMutableDictionary dictionary];
NSString *contentType=[self MimeTypeOf:self.request.URL.pathExtension];
NSString *contentLength=[NSString stringWithFormat:@"%lu", (unsigned long)data.length];
headers[@"Content-Type"]=contentType;
headers[@"Content-Length"]=contentLength;
NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc]
initWithURL:self.request.URL
statusCode:200
HTTPVersion:@"HTTP/1.1"
headerFields:headers];
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[self.client URLProtocol:self didLoadData:data];
[self.client URLProtocolDidFinishLoading:self];
} else {
self.connection = [NSURLConnection connectionWithRequest:proxyRequest delegate:self];
}
}