- 一.使用.bundle存放HTML代码
- 1、新建一个www文件夹,将HTML文件拷贝到www文件夹下面,然后将文件夹的名字改成www.bundle,如下图
- 2、将www.bundle拖到工程里
- 3、上代码,web view加载HTML,此方法会加载www.bundle中的index.html页面
-(void)createCustomUI
{
self.view.backgroundColor = [UIColor whiteColor];
self.automaticallyAdjustsScrollViewInsets = NO;
_webView = [[UIWebView alloc] init];
_webView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-20);
_webView.delegate = self;
[self.view addSubview:_webView];
//首先获取到www.bundle
NSString *bundleString = [[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:@"www.bundle"];
NSBundle *bundle = [NSBundle bundleWithPath:bundleString];
//其次,获取到www.bundle下的index.html的路径
NSString *urlString = [bundle pathForResource:@"index" ofType:@"html"];
//加载webview
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
}
- 二、使用SSZipArchive解压zip压缩包,获取HTML代码(SSZipArchive github地址 https://github.com/ZipArchive/ZipArchive)
- 1、新建一个www文件夹,将HTML文件拷贝到www文件夹下面,压缩成www.zip文件,将www.zip压缩包拖到工程里
-
2、添加SSZipArchive第三方库,依赖于libz.tdb
- 3、上代码,通过用SSZipArchive第三方库,将www.zip解压成www文件夹存放到沙盒里,然后加载HTML
@property (nonatomic, strong) UIWebView *webView; //webview
@property(copy , nonatomic)NSString *documentPath;//沙盒里documents文件夹路径
-(void)viewDidLoad {
[super viewDidLoad];
//加载页面
[self createCustomUI];
//SSZipArchive解压www.zip
[self performSelectorInBackground:@selector(unzip) withObject:nil];
}
-(void)createCustomUI
{
self.view.backgroundColor = [UIColor whiteColor];
self.automaticallyAdjustsScrollViewInsets = NO;
_webView = [[UIWebView alloc] init];
_webView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-20);
_webView.delegate = self;
[self.view addSubview:_webView];
}
//通过比较不同的版本号,来判断是否进行解压操作
-(void)unzip
{
NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
if ([dict[@"CFBundleShortVersionString"] isEqual:[[NSUserDefaults standardUserDefaults] objectForKey:@"VersionString"]]) {
//无操作
}
else {
NSString *zipPath = [[NSBundle mainBundle] pathForResource:@"www" ofType:@"zip"];
NSString *destinationPath = self.documentPath;
//将www.zip解压到沙盒里
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
//保存当前版本号
[[NSUserDefaults standardUserDefaults] setObject:dict[@"CFBundleShortVersionString"] forKey:@"VersionString"];
}
//加载index.html
[self performSelectorOnMainThread:@selector(showHtml) withObject:nil waitUntilDone:NO];
}
//懒加载,取得documents
-(NSString *)documentPath
{
if (_documentPath == nil) {
_documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
}
return _documentPath;
}
//加载沙盒中documents/www/index.html页面
-(void)showHtml
{
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[self.documentPath stringByAppendingString:@"/www/index.html"]]]];
}