1

我为基于 UIWebView 的应用程序注册了一个 NSURLProtocol,设置为响应file方案请求。

在 web 视图中,我加载图像、CSS、JS 等,一切正常;当我尝试引用不在 HTML 树根目录中的 CSS 文件中的图像时,问题就出现了。例如

<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>

查看到达我的 NSURLProtocol 的请求,我看不到确定请求文件在源树中的位置的方法。

例如,如果上面的 HTML 在一个名为 的文件中,我的 NSURLProtocol 子类将从该文件中source/index.html获取一个请求。../2.pngsource/css/style.css

这应该解析为source/2.png,但我不知道路径中应该css包含那个子目录。

有什么方法可以获取有关请求源的更多上下文,以便在查找请求的文件时修复路径?

4

1 回答 1

0

我有一个非常相似的问题,在这里解释:Loading resources from relative paths through NSURLProtocol subclass

我有以下内容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:43:40.863 回答