通过 NSURLProtocol 子类从相对路径加载资源 [英] Loading resources from relative paths through NSURLProtocol subclass
问题描述
我为基于 UIWebView 的应用注册了 NSURLProtocol,设置为响应 file
方案请求.
I have an NSURLProtocol registered for a UIWebView-based app, set up to respond to file
scheme requests.
在网络视图中,我加载图像、CSS、JS 等,一切正常;当我尝试引用不在 HTML 树根目录中的 CSS 文件中的图像时,问题就出现了.例如
In the web view, I load images, CSS, JS etc. and all that's all working fine; the problem comes when I try to reference an image in a CSS file that's not at the root directory of the HTML tree. E.g.
<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 的请求,我无法确定请求文件在我的源树中的位置.
Looking at the requests arriving at my NSURLProtocol, I can't see a way of determining where in my source tree the requesting file sits.
例如,如果上述 HTML 位于名为 source/index.html
的文件中,我的 NSURLProtocol 子类将从source/css/style.css
文件.
For example, if the above HTML was in a file called source/index.html
, my NSURLProtocol subclass would get a request for ../2.png
from the source/css/style.css
file.
这应该解析为 source/2.png
,但我不知道路径中应该包含 css
子目录.
This should resolve to source/2.png
, but I can't tell there should be that css
subdirectory included in the path.
有什么方法可以获得有关请求来源的更多上下文,以便在查找请求的文件时修复路径?
Is there any way to get more context about the source of a request, so that I fix up the paths when I look for the requested file?
推荐答案
我有一个非常相似的问题,在此处解释:通过NSURLProtocol子类从相对路径加载资源
I had a quite similar issue, explained here: Loading resources from relative paths through NSURLProtocol subclass
我的 NSURLProtocol
中有以下内容:
I had the following in my 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;
,来自
Where _lastReqURL is _lastReqURL = request.URL;
, from
- (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
}
}
我只能假设 NSURLResponse 中的 URL 部分在处理相对路径时很重要(似乎合乎逻辑).
I can only assume the URL part in NSURLResponse is critical when dealing with relative-paths (seems logical).
这篇关于通过 NSURLProtocol 子类从相对路径加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!