通过NSURLProtocol子类从相对path加载资源

我有一个NSURLProtocol注册为基于UIWebView的应用程序,设置为响应filescheme请求。

在Web视图中,我加载图像,CSS,JS等所有这一切工作正常; 当我尝试引用不在HTML树的根目录下的CSS文件中的图像时,问题就出现了。 例如

 <html> <head> <style type="text/css"> .1 { background-image: url("1.png"); } </style> <link href="css/style.css" rel="stylesheet" type="text/css" /> <!-- contents of css/style.css might be: .2 { background-image: url("../2.png"); } --> </head> <body> <div class="1">properly styled</div> <div class="2">not styled</div> </body> </head> 

看看到达我的NSURLProtocol的请求,我看不到确定请求文件位于源代码树中哪里的方法。

例如,如果上面的HTML在一个名为source/index.html的文件中,我的NSURLProtocol子类将从source/css/style.css文件中获取对../2.png的请求。

这应该解决source/2.png ,但我不能告诉应该有该path中包含的css子目录。

有什么方法可以获得更多关于请求源的上下文,以便在查找请求的文件时修复path?

我有一个相当类似的问题,在这里解释: 通过NSURLProtocol子类从相对path加载资源

我在NSURLProtocol有以下NSURLProtocol

 - (void)startLoading { [self.client URLProtocol:self didReceiveResponse:[[NSURLResponse alloc] init] cacheStoragePolicy:NSURLCacheStorageNotAllowed]; //Some other stuff } 

并解决了以下问题:

 - (void)startLoading { [self.client URLProtocol:self didReceiveResponse:[[NSURLResponse alloc] initWithURL:_lastReqURL MIMEType:nil expectedContentLength:-1 textEncodingName:nil] cacheStoragePolicy:NSURLCacheStorageNotAllowed]; //Some other stuff } 

其中_lastReqURL是_lastReqURL = request.URL;

 - (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id < NSURLProtocolClient >)client { self = [super initWithRequest:request cachedResponse:cachedResponse client:client]; if (self) { _lastReqURL = request.URL; // Some stuff } } 

我只能假设在处理相对path时,NSURLResponse中的URL部分是非常重要的(似乎是合乎逻辑的)。