一、版本
8系统前,用UIWebView
8系统后,用webkit,WKWebView
因为webkit有两大优点:
1、占用内存更小,
2、可以通过回调直接捕捉网页上的alert,输入等js操作
二、代码
第一部分:UIViewController
//
// ViewController.m
// WKWebView
//
// Created by nnandzc on 16/11/6.
// Copyright © 2016 年 nnandzc. All rights reserved.
//
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
@interface ViewController ()
<
WKUIDelegate ,
WKNavigationDelegate ,
WKScriptMessageHandler
>
@property ( nonatomic , strong ) WKWebView *webView;
@property ( nonatomic , strong , readonly ) JSContext *jsContext;
@end
@implementation ViewController
- ( void )viewDidLoad {
[ super viewDidLoad ];
[ self webView ];
}
- ( WKWebView *)webView
{
if (! _webView )
{
// js 配置
WKUserContentController *userContentController = [[ WKUserContentController alloc ] init ];
[userContentController addScriptMessageHandler : self name : @"jsCallOC" ];
// WKWebView 的配置
WKWebViewConfiguration *configuration = [[ WKWebViewConfiguration alloc ] init ];
configuration. userContentController = userContentController;
_webView = [[ WKWebView alloc ] initWithFrame : self . view . bounds configuration :configuration];
_webView . navigationDelegate =
// ViewController.m
// WKWebView
//
// Created by nnandzc on 16/11/6.
// Copyright © 2016 年 nnandzc. All rights reserved.
//
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
@interface ViewController ()
<
WKUIDelegate ,
WKNavigationDelegate ,
WKScriptMessageHandler
>
@property ( nonatomic , strong ) WKWebView *webView;
@property ( nonatomic , strong , readonly ) JSContext *jsContext;
@end
@implementation ViewController
- ( void )viewDidLoad {
[ super viewDidLoad ];
[ self webView ];
}
- ( WKWebView *)webView
{
if (! _webView )
{
// js 配置
WKUserContentController *userContentController = [[ WKUserContentController alloc ] init ];
[userContentController addScriptMessageHandler : self name : @"jsCallOC" ];
// WKWebView 的配置
WKWebViewConfiguration *configuration = [[ WKWebViewConfiguration alloc ] init ];
configuration. userContentController = userContentController;
_webView = [[ WKWebView alloc ] initWithFrame : self . view . bounds configuration :configuration];
_webView . navigationDelegate =