通过WebView加载网页展示效果图:
目录
1.2.1 使用loadHTMLString加载本地html页面
WKWebView
移动端目前对于H5的使用越来越广泛了,随着5G时代的到来,网络提速,WebView在移动端的使用只会更加多。Android端使用WebView这个控件加载HTML+CSS+JS,IOS类似,目前使用的是WKWebView,之前UIWebView目前已经过时了,UIWebView在使用过程中对于内存开销比较大,而且加载速度也存在问题,WKWebView替代了UIWebView解决了这两个问题。
WKWebView内存占用23M,而UIWebView内存占用85M;允许JavaScript的Nitro库加载并使用(UIWebView中限制);支持了更多的H5特性;支持高达60fps的滚动刷新率以及内置手势;
WKWebView的使用
WKWebView加载的内容可以是网络资源也可以是本地的html页面。
1.1 WKWebView加载网络数据
WKWebView网络数据的加载可以调用loadRequest函数,如下:
- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
布局如下图,红色矩形框是WKWebView,当点击“加载网络数据”Button的时候显示简述的界面:
1.1.1 WKWebView使用报错问题
在学习的过程中遇到一个比较坑的问题,如下
通过故事板拖拽布局一个WKWebview,两个UIButton,然后拖拽通过Outlets在ViewController中自动生成属性变量mWebView、localButton和netButtton,给netButtton这个按钮添加一个事件,在事件调用的函数中使用loadRequest加载网页,运行代码直接报错无法进入应用,错误信息如下:
2019-04-16 20:31:11.810262+0800 WebView[24662:890526] libMobileGestalt MobileGestalt.c:890: MGIsDeviceOneOfType is not supported on this platform.
2019-04-16 20:31:11.881966+0800 WebView[24662:890526] *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named WKWebView'
*** First throw call stack:
(
0 CoreFoundation 0x000000010c8ce1bb __exceptionPreprocess + 331
1 libobjc.A.dylib 0x000000010be6c735 objc_exception_throw + 48
2 CoreFoundation 0x000000010c8ce015 +[NSException raise:format:] + 197
3 UIFoundation 0x00000001152d0427 UINibDecoderDecodeObjectForValue + 359
4 UIFoundation 0x00000001152d02b3 -[UINibDecoder decodeObjectForKey:] + 251
5 UIKitCore 0x000000010f3a47b8 -[UIRuntimeConnection initWithCoder:] + 178
6 UIFoundation 0x00000001152d05ad UINibDecoderDecodeObjectForValue + 749
7 UIFoundation 0x00000001152d0854 UINibDecoderDecodeObjectForValue + 1428
8 UIFoundation 0x00000001152d02b3 -[UINibDecoder decodeObjectForKey:] + 251
9 UIKitCore 0x000000010f3a2067 -[UINib instantiateWithOwner:options:] + 1220
10 UIKitCore 0x000000010f115452 -[UIViewController _loadViewFromNibNamed:bundle:] + 383
11 UIKitCore 0x000000010f115ddc -[UIViewController loadView] + 177
12 UIKitCore 0x000000010f1160ee -[UIViewController loadViewIfRequired] + 175
13 UIKitCore 0x000000010f116940 -[UIViewController view] + 27
14 UIKitCore 0x000000010f76dc53 -[UIWindow addRootViewControllerViewIfPossible] + 122
15 UIKitCore 0x000000010f76e36e -[UIWindow _setHidden:forced:] + 294
16 UIKitCore 0x000000010f7815c0 -[UIWindow makeKeyAndVisible] + 42
17 UIKitCore 0x000000010f72e833 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4595
18 UIKitCore 0x000000010f733c2f -[UIApplication _runWithMainScene:transitionContext:completion:] + 1623
19 UIKitCore 0x000000010ef524e9 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 866
20 UIKitCore 0x00000