WKWebView和UIWebView的区别
总结起来几点:
- 内存占用变小
- 支持更多的HTML5特性
- 高刷新
- Safari相同的JavaScript引擎
- 加载速度变快
配置
- WKWebViewConfiguration
// 当前所属进程池
// WKProcessPool用来配置进程池,与网页视图的资源共享有关
@property (nonatomic, strong) WKProcessPool *processPool;
// 偏好设置
@property (nonatomic, strong) WKPreferences *preferences;
WKPreferences-> propertys
//最小字体
@property (nonatomic) CGFloat minimumFontSize;
//是否可以打开没有用户交互的窗口
@property (nonatomic) BOOL javaScriptCanOpenWindowsAutomatically;
// 是否应警告可疑性的欺诈内容,(钓鱼网站或恶意软件)
@property (nonatomic, getter=isFraudulentWebsiteWarningEnabled) BOOL fraudulentWebsiteWarningEnabled API_AVAILABLE(macos(10.15), ios(13.0));
//是否开启文字互动
@property (nonatomic) BOOL textInteractionEnabled API_AVAILABLE(macos(11.3), ios(14.5));
WKUserContentController:OC与JS交互
@property (nonatomic, strong) WKUserContentController *userContentController;
WKWebsiteDataStore:网页使用到的数据管理类
@property (nonatomic, strong) WKWebsiteDataStore *websiteDataStore API_AVAILABLE(macos(10.11), ios(9.0));
指示网络视图是否在【内容渲染完全加载到内存之前】禁止内容呈现,默认是NO。
@property (nonatomic) BOOL suppressesIncrementalRendering;
在用户代理字符串中使用的应用程序的名称。
@property (nullable, nonatomic, copy) NSString *applicationNameForUserAgent API_AVAILABLE(macos(10.11), ios(9.0));
是否支持airplay
@property (nonatomic) BOOL allowsAirPlayForMediaPlayback API_AVAILABLE(macos(10.11), ios(9.0));
枚举类型,需要用户手势开始播放的媒体类型
@property (nonatomic) WKAudiovisualMediaTypes mediaTypesRequiringUserActionForPlayback API_AVAILABLE(macos(10.12), ios(10.0));
默认网页偏好设置
@property (null_resettable, nonatomic, copy) WKWebpagePreferences *defaultWebpagePreferences API_AVAILABLE(macos(10.15), ios(13.0));
限制app跳转
@property (nonatomic) BOOL limitsNavigationsToAppBoundDomains API_AVAILABLE(macos(11.0), ios(14.0));
指示HTML5视频是否内嵌播放,或使用native全屏控制器。
@property (nonatomic) BOOL allowsInlineMediaPlayback;
设置选择粒度 用户可以在网页视图中交互地选择内容的粒度级别。
@property (nonatomic) WKSelectionGranularity selectionGranularity;
HTML5视图是否可以播放画中画
@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback API_AVAILABLE(ios(9_0));
识别数据类型 所需的数据监测类型。
@property (nonatomic) WKDataDetectorTypes dataDetectorTypes API_AVAILABLE(ios(10.0));
用于确定WKWebView是否应始终允许缩放网页。
@property (nonatomic) BOOL ignoresViewportScaleLimits API_AVAILABLE(ios(10.0));
#else
选择用户界面方向 用户界面元素的方向。
@property (nonatomic) WKUserInterfaceDirectionPolicy userInterfaceDirectionPolicy API_AVAILABLE(macos(10.12));
#endif
设置拦截的Scheme和对应回调
- (void)setURLSchemeHandler:(nullable id <WKURLSchemeHandler>)urlSchemeHandler forURLScheme:(NSString *)urlScheme API_AVAILABLE(macos(10.13), ios(11.0));
获取scheme对应回调
- (nullable id <WKURLSchemeHandler>)urlSchemeHandlerForURLScheme:(NSString *)urlScheme API_AVAILABLE(macos(10.13), ios(11.0));
OC与JS通讯
- 相互调用的基础是通讯协议(方法名、参数类型),通常都是JS端和OC端根据业务逻辑来共同制定
以下代码是对和通讯的一个简单封装
#import <Foundation/Foundation.h>
@protocol WAExcuteScriptDelegate <NSObject>
- (void)excuteScript:(NSString *_Nonnull)script complition:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))complition;
@end
typedef void(^MessageHandle)(id _Nonnull body, NSString * _Nonnull name);
@class WKUserContentController;
NS_ASSUME_NONNULL_BEGIN
@interface WAScriptProcesser : NSObject
@property (nonatomic, weak) id<WAExcuteScriptDelegate> excuteDelegate;
@property (nonatomic, strong) WKUserContentController *userController;
// 脚本注入
- (void)addScript:(NSString *)script
atStart:(BOOL)atStart
isFrameMain:(BOOL)isFrameMain;
/** oc->js
@param script 执行js中定义的函数 :getName('name');
@param complition 完成回调
*/
- (void)excuteScript:(NSString *)script complition:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))complition;
/** js->oc
* @param name : 注册和 js 约定好的回调名称
* @param complition 回调
*/
- (void)registerHandleWithName:(NSString *)name complition:(MessageHandle)complition;
@end
NS_ASSUME_NONNULL_END
//
// WAScriptProcesser.m
// JSView
//
// Created by admin on 2021/11/12.
//
#import "WAScriptProcesser.h"
#import <WebKit/WebKit.h>
@interface WAScriptProcesser ()<WKScriptMessageHandlerWithReply,WKScriptMessageHandler>
@property (nonatomic, strong) NSMutableDictionary *handleDict;
@end
@implementation WAScriptProcesser
- (NSMutableDictionary *)handleDict
{
if (_handleDict == nil)
{
_handleDict = [[NSMutableDictionary alloc] init];
}
return _handleDict;
}
- (WKUserContentController *)contentController
{
if (_userController == nil)
{
_userController = [[WKUserContentController alloc] init];
}
return _userController;
}
- (void)addScript:(NSString *)script
atStart:(BOOL)atStart
isFrameMain:(BOOL)isFrameMain
{
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:script injectionTime:atStart?WKUserScriptInjectionTimeAtDocumentStart:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:isFrameMain];
[self.userController addUserScript:userScript];
}
- (void)excuteScript:(NSString *)script complition:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))complition
{
[self.excuteDelegate excuteScript:script complition:complition];
}
- (void)registerHandleWithName:(NSString *)name complition:(MessageHandle)complition
{
[self.userController addScriptMessageHandler:self name:name];
[self.handleDict setValue:[complition copy] forKey:name];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message replyHandler:(void (^)(id _Nullable reply, NSString *_Nullable errorMessage))replyHandler WK_SWIFT_ASYNC(3) API_AVAILABLE(macos(11.0), ios(14.0))
{
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSString *name = message.name;
id body = message.body;
MessageHandle block = (MessageHandle)[self.handleDict objectForKey:name];
if (block)
{
block(body, name);
}
}
@end
Scheme拦截
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
typedef void(^RouterHandler)(BOOL isStart, id <WKURLSchemeTask> _Nonnull urlSchemeTask, NSDictionary * _Nonnull params);
NS_ASSUME_NONNULL_BEGIN
@interface WARouter : NSObject
- (void)registerPattern:(NSString *)pattern handle:(RouterHandler)handle;
@end
NS_ASSUME_NONNULL_END
#import "WARouter.h"
@interface WARouter ()<WKURLSchemeHandler>
@property (nonatomic, strong) NSMutableDictionary *routers;
@end
@implementation WARouter
- (NSMutableDictionary *)routers
{
if (_routers == nil)
{
_routers = [[NSMutableDictionary alloc] init];
}
return _routers;
}
- (void)registerPattern:(NSString *)pattern handle:(RouterHandler)handle
{
[self.routers setValue:[handle copy] forKey:pattern];
}
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask
{
NSURL *url = urlSchemeTask.request.URL;
NSString *scheme = url.scheme;
NSArray *pairs = [url.query componentsSeparatedByString:@"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *str in pairs)
{
NSArray *pair = [str componentsSeparatedByString:@"="];
[params setValue:[pair lastObject] forKey:[pair firstObject]];
}
[params addEntriesFromDictionary:urlSchemeTask.request.allHTTPHeaderFields];
RouterHandler handler = [self.routers objectForKey:scheme];
handler(YES, urlSchemeTask, params);
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask
{
NSURL *url = urlSchemeTask.request.URL;
NSString *scheme = url.scheme;
NSArray *pairs = [url.query componentsSeparatedByString:@"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *str in pairs)
{
NSArray *pair = [str componentsSeparatedByString:@"="];
[params setValue:[pair lastObject] forKey:[pair firstObject]];
}
[params addEntriesFromDictionary:urlSchemeTask.request.allHTTPHeaderFields];
RouterHandler handler = [self.routers objectForKey:scheme];
handler(NO, urlSchemeTask, params);
}
@end
WKWebview的优化和坑,参考如下
https://juejin.cn/post/6861778055178747911
https://segmentfault.com/a/1190000039111381
https://cloud.tencent.com/developer/article/1005691
WKWebview API全解
https://cloud.tencent.com/developer/article/1485172