如何加载 javascript 文件的本地版本而不是远程版本?

How can I load a local version of a javascript file instead of a remote version?

我想加载一个包含巨大 javascript 文件的网页。

<script src="js/sample.js"></script>

我无法更改 html 文件,但我可以将 javascript 文件下载到我的应用程序。

NSString* path = [NSString stringWithFormat:@"http://www.demo.url/index.html"];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[webView loadRequest:request];

每次我启动我的应用程序时,chached javascript 文件都必须重新加载。也许我有错误的缓存设置。

两种可能的解决方案:

  1. 以正确的方式缓存javascipt。不要在应用程序关闭时删除。
  2. 手动下载javascript文件并使用。

您要注入 javascript 吗?

[webView stringByEvaluatingJavaScriptFromString:jsString];

如果您是第一次尝试加载本地 html 文件,请将其添加到包中并命名为:

NSURL *relativeURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSURL *u = [NSURL URLWithString:@"xxx.html" relativeToURL:relativeURL];

然后当您需要重新加载时,您可以执行正常的 uiwebview 请求方法调用!

我找到了解决方案:

实现自己的 NSURL 协议:

NSURLProtocolCustom.h

#import <Foundation/Foundation.h>
@interface NSURLProtocolCustom : NSURLProtocol<NSURLConnectionDelegate> {
    NSMutableData *responseData;
}
@property (nonatomic, strong) NSURLConnection *connection;
@end

NSURLProtocolCustom.m

#import "NSURLProtocolCustom.h"
@implementation NSURLProtocolCustom
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if ([[request.URL lastPathComponent] isEqualToString:--Your precached file--]) { 
        return true;
    } else {
        return false;
    }
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

- (void)startLoading {
    NSString* file = --Your local file--;
    NSData *data = [NSData dataWithContentsOfFile:file];
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[self.request URL] MIMEType:@"text/javascript" expectedContentLength:-1 textEncodingName:nil];
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)stopLoading {
}

还有你的要求

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:--your URL-- cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:50.0];
[NSURLProtocol registerClass:[NSURLProtocolCustom class]];