我为基于UIWebView的应用注册了NSURLProtocol,设置为响应file
方案请求。
在网页视图中,我加载图像,CSS,JS等等,所有这些都正常工作;当我尝试引用不在HTML树根目录下的CSS文件中的图像时出现问题。 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的请求,我看不到确定请求文件在源树中的位置的方法。
例如,如果上面的HTML位于名为source/index.html
的文件中,我的NSURLProtocol子类将从../2.png
文件中获得source/css/style.css
的请求。
这应解析为source/2.png
,但我不知道路径中是否应包含css
子目录。
有没有办法获得有关请求源的更多上下文,以便在查找请求的文件时修复路径?
答案 0 :(得分:0)
我有一个非常相似的问题,在此解释:Loading resources from relative paths through NSURLProtocol subclass
我的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
}
}
我只能假设NSURLResponse中的URL部分在处理相对路径时很重要(似乎是合乎逻辑的)。