1

我实现了一个自定义的 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,缺少资产部分。如果我将..部分切换为,它工作正常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)
4

2 回答 2

1

终于修好了。

我有以下内容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-02T08:42:31.453 回答
0

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

例如以下:

[self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"host"]];
于 2014-04-01T09:42:19.620 回答