gpt4 book ai didi

ios - NSURLProtocol 和相对路径

转载 作者:行者123 更新时间:2023-11-29 12:49:25 24 4
gpt4 key购买 nike

我实现了一个自定义 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 部分。如果我切换 .. 它工作正常部分 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)

最佳答案

终于修好了。

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

关于ios - NSURLProtocol 和相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com