问题
I have an NSURLProtocol registered for a UIWebView-based app, set up to respond to file
scheme requests.
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>
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.
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.
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?
回答1:
I had a quite similar issue, explained here: Loading resources from relative paths through NSURLProtocol subclass
I had the following in my NSURLProtocol
:
- (void)startLoading {
[self.client URLProtocol:self
didReceiveResponse:[[NSURLResponse alloc] init]
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
//Some other stuff
}
and solved the issue with the following :
- (void)startLoading {
[self.client URLProtocol:self
didReceiveResponse:[[NSURLResponse alloc] initWithURL:_lastReqURL MIMEType:nil expectedContentLength:-1 textEncodingName:nil]
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
//Some other stuff
}
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
}
}
I can only assume the URL part in NSURLResponse is critical when dealing with relative-paths (seems logical).
来源:https://stackoverflow.com/questions/11874795/loading-resources-from-relative-paths-through-nsurlprotocol-subclass