我想加载一个包含巨大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文件都必须重新加载。也许我有错误的缓存设置。
两种可能的解决方案:
答案 0 :(得分:0)
[webView stringByEvaluatingJavaScriptFromString:jsString];
如果您是第一次尝试加载本地html文件,请将其添加到捆绑包中并将其称为谎言:
NSURL *relativeURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSURL *u = [NSURL URLWithString:@"xxx.html" relativeToURL:relativeURL];
然后当你需要重新加载时,你做一个正常的uiwebview请求方法调用!
答案 1 :(得分:0)
我找到了解决方案:
实施自己的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]];