Ios 通过NSURLProtocol子类从相对路径加载资源
我为基于UIWebView的应用程序注册了NSURL协议,设置为响应Ios 通过NSURLProtocol子类从相对路径加载资源,ios,uiwebview,webview,nsurlprotocol,Ios,Uiwebview,Webview,Nsurlprotocol,我为基于UIWebView的应用程序注册了NSURL协议,设置为响应文件方案请求 在web视图中,我加载图像、CSS、JS等,所有这些都可以正常工作;当我试图引用CSS文件中不在HTML树根目录下的图像时,就会出现问题。例如 <html> <head> <style type="text/css"> .1 { background-image: url("1.png"); } </style>
文件
方案请求
在web视图中,我加载图像、CSS、JS等,所有这些都可以正常工作;当我试图引用CSS文件中不在HTML树根目录下的图像时,就会出现问题。例如
<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>
.1{背景图像:url(“1.png”);}
风格得体
不时尚
查看到达NSURLProtocol的请求,我无法确定请求文件在源代码树中的位置
例如,如果上面的HTML位于一个名为source/index.HTML
的文件中,那么我的NSURLProtocol子类将从source/css/style.css
文件中获得一个对./2.png
的请求
这应该解析为source/2.png
,但我不能确定路径中应该包含css
子目录
有没有办法获得更多关于请求源的上下文信息,以便在查找请求文件时修复路径?我遇到了一个非常类似的问题,如下所述: 我的
nsurl协议中包含以下内容:
- (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
}
}
-(id)initWithRequest:(NSURLRequest*)请求缓存响应:(NSCachedURLResponse*)缓存响应客户端:(id)客户端{
self=[super initWithRequest:request cachedResponse:cachedResponse client:client];
如果(自我){
_lastReqURL=request.URL;
//一些东西
}
}
我只能假设NSURLResponse中的URL部分在处理相对路径时是关键的(似乎合乎逻辑)