通过NSURLProtocol子类从相对路径加载资源

我为基于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位于名为source/index.html的文件中,我的NSURLProtocol子类将从source/css/style.css文件中获取对../2.png的请求。

这应该解决source/2.png ,但我不能告诉应该有该路径中包含该css子目录。

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


我有一个非常类似的问题,在这里解释:通过NSURLProtocol子类从相对路径加载资源

我在我的NSURLProtocol有以下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部分非常重要(看起来很合理)。

链接地址: http://www.djcxy.com/p/34841.html

上一篇: Loading resources from relative paths through NSURLProtocol subclass

下一篇: Use AFNetworking with custom NSURLProtocol class