列表内容
webView加载本地html,大多数人可能会遇到图片加载不出来的问题!这是html的图片路径和运行后包内容的图片路径不一样的原因!因此我用的方法是把要加载的html文件弄成压缩文件,将这个文件存放在Document,然后进行解压,读取Document里边的解压后的文件,这样就可以防止图片路径错误!
用到的第三方库ZipArchive[第三方库下载]
http://pan.baidu.com/s/1c02icWo“>ZipArchive[第三方库下载]
第一步 导入ZipArchive库,在需要用的页面导入头文件ZipArchive.h
第二步 导入html文件的压缩包XXX.zip
第三部 如下代码
//注意事件
//第三方库需要导入libz.dylib
//解压后可以前往document文件夹查看解压后的效果,根据解压后文件夹的名字进行关
键地方的填写,思路就是这样
//如html页面出现的一切问题,皆为写html人的问题
//关于模拟器中成功(即模拟器中正常显示),真机上不成功(比例等其他地方的问题)
的原因,有可能是写html的人引用css文件或其他文件时大小写发生错误——–
一句话 html人的错误
NSString *itemPath = @"压缩包文件名";
NSArray *aArray = [itemPath componentsSeparatedByString:@"."];
NSString *filename = [aArray objectAtIndex:0];
NSString *sufix = [aArray objectAtIndex:1];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:filename ofType:sufix];
NSData *data = [NSData dataWithContentsOfFile:imagePath options:0 error:nil];
//存入 沙河路径中
NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [docPath objectAtIndex:0];
NSLog(@"Documents目录:%@",documentsPath);
//存入文件
if(!documentsPath){
NSLog(@"没找到相关路径");
}else{
NSString *fliePath = [documentsPath stringByAppendingString:[NSString stringWithFormat:@"/%@",itemPath]];
[data writeToFile:fliePath atomically:YES];
}
//读取文件
NSArray *myDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *myDocumentsPath = [myDocPath objectAtIndex:0];
NSString *readPath = [myDocumentsPath stringByAppendingPathComponent:itemPath];
//解压zip文件夹
ZipArchive* zip = [[ZipArchive alloc] init];
if( [zip UnzipOpenFile:readPath] ){
BOOL result = [zip UnzipFileTo:myDocumentsPath overWrite:YES];
if( NO==result ){
//添加代码
}
[zip UnzipCloseFile];
}
//读文件
NSString *zipReadPath = [myDocumentsPath stringByAppendingPathComponent:@"查看document下解压后的文件夹的名字/index.html"];//例如解压后的文件夹名字为 boke html的起始页面为index.html 此处@"boke/index.html"
NSString *htmlstring =[[NSString alloc] initWithContentsOfFile:zipReadPath encoding:NSUTF8StringEncoding error:nil];
_webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
_webView.backgroundColor = [UIColor blackColor];
NSString *url = [myDocumentsPath stringByAppendingPathComponent:@"解压后文件夹的名字/"];
[_webView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:url]];
//url是当前文件夹的路径 即为document路径拼接文件夹名字
NSLog(@"%@",htmlstring);
NSLog(@"%@",[NSURL fileURLWithPath:url]);
[self.view addSubview:_webView];
见证奇迹的时候,希望看到上面的童鞋不要打我
简单的方法
在导入HTML文件的时候一定要勾选下面的
然后按照普通的方法加载html
NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"文件夹名称/开始的html页面" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:filePath];
[_webView loadRequest:request];