我实现了一个定制的NSURLProtocol,它允许我使用网站的静态压缩版本作为webView的目标。它在执行过程中打开zip并加载所需的数据。但问题是,NSURLProtocol似乎没有正确地使用相对路径?也就是说,我有以下结构:
assets/css/main.css
assets/css/style.css
assets/images/sprite.png
index.html并使用: sprite.png从css调用background: url(../images/sprite.png) no-repeat;,但是,我的自定义NSURLProtocol中的requestURL显示了方案://host/requestURL/sprite.png,缺少了资产部分。如果我将..部件转换为assets,它可以正常工作,但我不希望这样做。
我在这里发现了同样的问题:Loading resources from relative paths through NSURLProtocol subclass,但这个问题没有答案。
我找不到任何方法来解决这个问题,这样请求就能正确地解决相对路径,或者事后自己修复路径(但是我需要知道请求来自哪里,那里也没有运气)。
任何帮助都很感谢,谢谢。
附带注意:在@import url("style.css");中使用main.css的相同问题
编辑:
我首先从远程服务器下载zip文件:
NSURL * fetchURL = [NSURL URLWithString:zipURLString];
[…]
NSString * filePath = [[self documentsDirectory] stringByAppendingPathComponent:fetchURL.path.lastPathComponent];
[zipData writeToFile:filePath atomically:YES];所以,从http://host/foo/archive.zip,我把它保存到documentsDirectory/archive.zip。在那里,我将方案和url更改为指向zip文件:
NSString * str = [NSString stringWithFormat:@"myzip://%@", zipURL.path.lastPathComponent];
[_webView loadRequest:[NSURLRequest str]];它打开myzip://archive.zip,如果在zip文件中没有找到这样的文件,我将/index.html追加到当前路径。因此,以下请求到达我的NSURLProtocol子类- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id < NSURLProtocolClient >)client:
myzip://archive.zip (Changed to myzip://archive.zip/index.html)
myzip://archive.zip/assets/css/main.css
myzip://archive.zip/styles.css (Problem here)发布于 2014-04-02 08:42:31
终于修好了。
我的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辅助部分在处理相对路径时是非常关键的(似乎合乎逻辑)。
发布于 2014-04-01 09:42:19
我认为这可能是指加载请求或HTML的方式。你能为你的请求粘贴代码吗?我想,您是在本地加载HTML的,所以不要忘记相应地设置baseURL,否则相对路径将不再工作:
例如,以下内容:
[self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"host"]];https://stackoverflow.com/questions/22781523
复制相似问题