cordova加载服务器H5页面,js放本地

首先需要改造一下cordova文件源码
CDVURLProtocol.m这个文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//重写方法
-(void)startLoading
{
//处理自定义标签 ,并实现内嵌本地资源
NSLog(@"startLoading");
NSLog(@"%@", super.request.URL);
NSString *url=super.request.URL.resourceSpecifier;// 得到//image1.png"
//去掉 //前缀()
url=[url substringFromIndex:2];//image1.png
NSString *path= [[NSBundle mainBundle] pathForResource:url ofType:nil];//这里是获取本地资源路径 如 :png,js 等
if (!path) {
[self sendResponseWithResponseCode:401 data:nil mimeType:nil];//重要
return;
}
//根据路径获取MIMEType (以下函数方法需要添加.h文件的引用,)
// Get the UTI from the file's extension:
CFStringRef pathExtension = (__bridge_retained CFStringRef)[path pathExtension];
CFStringRef type = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, NULL);
CFRelease(pathExtension);
// The UTI can be converted to a mime type:
NSString *mimeType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass(type, kUTTagClassMIMEType);
if (type != NULL)
CFRelease(type);
// 这里需要用到MIMEType
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:super.request.URL
MIMEType:mimeType
expectedContentLength:-1
textEncodingName:nil];
NSData *data = [NSData dataWithContentsOfFile:path];//加载本地资源
[self sendResponseWithResponseCode:200 data:data mimeType:mimeType];
//硬编码 开始嵌入本地资源到web中
[[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}

这里使用之前要注册一下

1
2
3
4
[NSURLProtocol registerClass:[CDVURLProtocol class]];
TestViewController *test = [[TestViewController alloc]init];
test.wwwFolderName = @"";
test.startPage = @"http://localhost/www/index.html";

把按照cordova官网教程做的demo中,插件拖进来,注意这里,一定要选择Create folder references
工程中显示蓝色文件夹,在cordova_plugins.js中,自己设置导入的插件目录,差不多就这样了