NSURLProtocol和相对路径

时间:2014-04-01 09:16:50

标签: ios relative-path nsurlprotocol

我实现了一个自定义NSURLProtocol,允许我使用网站的静态压缩版本作为webView的目标。它随时打开zip并加载所需的数据。 但问题是NSURLProtocol似乎不能在相对路径上正常运行?那就是我有以下结构:

assets/css/main.css
assets/css/style.css
assets/images/sprite.png
index.html

使用以下命令从css调用sprite.png:background: url(../images/sprite.png) no-repeat; 但是,我的自定义NSURLProtocol中的requestURL显示scheme://host/images/sprite.png,缺少资产部分。如果我切换..的{​​{1}}部分,它可以正常工作,但我宁愿不必这样做。

我在这里发现了同样的问题:Loading resources from relative paths through NSURLProtocol subclass但是没有答案。

我找不到任何方法来解决这个问题,以便请求正确解析相对路径,或者之后自己修复路径(但我需要知道请求来自哪里,并且在那里也没有运气)

任何帮助表示感谢,提前谢谢。

旁注: 使用main.css中的assets

时出现同样的问题

修改:

我首先从远程服务器下载zip文件:

@import url("style.css");

因此,从NSURL * fetchURL = [NSURL URLWithString:zipURLString]; […] NSString * filePath = [[self documentsDirectory] stringByAppendingPathComponent:fetchURL.path.lastPathComponent]; [zipData writeToFile:filePath atomically:YES]; 开始,我将其保存到http://host/foo/archive.zip。 从那里,我改变方案和URL指向zip文件:

documentsDirectory/archive.zip

这会打开myzip://archive.zip,如果在zip文件中找不到这样的文件,我会将/index.html附加到当前路径。 因此,以下请求到达我的NSString * str = [NSString stringWithFormat:@"myzip://%@", zipURL.path.lastPathComponent]; [_webView loadRequest:[NSURLRequest str]]; 子类NSURLProtocol

- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id < NSURLProtocolClient >)client

2 个答案:

答案 0 :(得分:0)

我认为这可能是指您加载请求或HTML的方式。 你能粘贴你的请求的代码吗?我想,你在本地加载HTML,所以不要忘记相应地设置baseURL,否则相关的pathes将不再起作用了:

例如以下内容:

[self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"host"]];

答案 1 :(得分:0)

最后修好了。

我的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部分在处理相对路径时很重要(似乎是合乎逻辑的)。