这段时间开发IOS应用,自己本身是搞java web 和 android,搞ios应用后面还有好多坑要跳,所以学习一点就整理一点笔记。不敢保证内容都是对的,但至少,我尝试过分析整理的。
UIWebVIew和WKWebView都是ios提供的web控件。但是后者比前者性能更好,占用内存更少。但是使用起来确实没有前者方便,搞ios的开发人员几乎都会觉得wkwebview用起来事真多,在UIWebView中能用的在WKWebView中就不行,比如Cookie的问题。
WKWebView加载本地html文件比较简单,基本上就是模板代码。
//
// ViewController.m
// LoadHtml
//
// Created by 汝玉林 on 2018/2/7.
// Copyright © 2018年 witsystem. All rights reserved.
//
#import "ViewController.h"
#import <WebKit/WebKit.h>
//设备的宽高
#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height
@interface ViewController ()
@property (nonatomic, strong) WKWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化wkwebview
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0,SCREENWIDTH, SCREENHEIGHT)];
//添加到view中
[self.view addSubview: self.webView];
//获取bundlePath 路径
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
//获取本地html目录 basePath
NSString *basePath = [NSString stringWithFormat: @"%@/www", bundlePath];
//获取本地html目录 baseUrl
NSURL *baseUrl = [NSURL fileURLWithPath: basePath isDirectory: YES];
NSLog(@"%@", baseUrl);
//html 路径
NSString *indexPath = [NSString stringWithFormat: @"%@/index.html", basePath];
//html 文件中内容
NSString *indexContent = [NSString stringWithContentsOfFile:
indexPath encoding: NSUTF8StringEncoding error:nil];
//显示内容
[self.webView loadHTMLString: indexContent baseURL: baseUrl];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我的项目结构
如果html文件中引用图片、js、css文件可以写相对路径,如果还是获取不到外部资料说明baseUrl参数传递有问题。