澳门新葡亰娱乐网站-www.142net-欢迎您

澳门新葡亰娱乐网站是因为你还没有找到一条正确的致富之路,www.142net是将所有的游戏都汇集在一起的官方平台,因为澳门新葡亰娱乐网站这个网站当中有着大量的游戏攻略,托IP定位技术,传达终端直接到达的精准传播方式。

WKWebView的使用(一)

来源:http://www.bhtsgq.com 作者:计算机知识 人气:94 发布时间:2020-05-06
摘要:乘势iOS10的产出,大多数应用都早已裁撤了iOS7的扶持,那么将 UIWebView 替换为 WKWebView 的劳作也就提上了日程。究竟 UIWebView 的攻克内部存款和储蓄器大,并且存在走漏难点,满含对js的

乘势iOS10的产出,大多数应用都早已裁撤了iOS7的扶持,那么将UIWebView替换为WKWebView的劳作也就提上了日程。究竟UIWebView的攻克内部存款和储蓄器大,并且存在走漏难点,满含对js的帮衬也是不比WKWebView的,所以半数以上的UIWebView都应当替换为WKWebView

1.初始化

@interface BaiduViewController () <WKNavigationDelegate, WKUIDelegate>

@property (strong, nonatomic) WKWebView *webView;

@end


@implementation BaiduViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  // 图片缩放的js代码
    NSString *js = @"var count = document.images.length;for (var i = 0; i < count; i  ) {var image = document.images[i];image.style.width=320;};window.alert('加载'   count   '的图');";

    // 根据JS字符串初始化WKUserScript对象
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

    // 根据生成的WKUserScript对象,初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config.userContentController addUserScript:script];

    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    //_webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];

    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
}


#pragma mark - WKNavigationDelegate

/**
 *  在发送请求之前,决定是否跳转 01
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {


    // 是否允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}

/**
 *  页面开始加载时调用 02
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

}

/**
 *  在收到响应后,决定是否跳转 03
 *
 *  @param webView            实现该代理的webview
 *  @param navigationResponse 当前navigation
 *  @param decisionHandler    是否跳转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

    NSString *lowercaseString = navigationResponse.response.URL.host.lowercaseString ;
     // 是否允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
}


/**
 *  当内容开始返回时调用 04
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}

/**
 *  页面加载完成之后调用 05
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}

/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
}

/**
 *  接收到服务器跳转请求之后调用
 *
 *  @param webView      实现该代理的webview
 *  @param navigation   当前navigation
 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {

}

#pragma mark - WKUIDelegate

/**
 *  web界面中有弹出警告框时调用
 *
 *  @param webView           实现该代理的webview
 *  @param message           警告框中的内容
 *  @param frame             主窗口
 *  @param completionHandler 警告框消失调用
 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

    [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil] show];

    completionHandler();
}

//运行JavaScript确认面板与消息
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {

    NSLog(@"message%@",message);
}

//运行JavaScript确认面板与消息
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    NSLog(@"defaultText%@",defaultText);

}

// 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

    NSLog(@"%@", message);
}



@end

出于大家的工程对js只进行了简便易行的支撑和调用,并从未太多复杂的人机联作,这里就不对WKUIDelegate进行验证了,毕竟自个儿亦不是很明亮。这里大约说一下笔者在轮番进程中遭逢的一对主题素材吧:

_webView = [[WKWebView alloc]WKWebView的使用(一)。initWithFrame:CGRectMake(0,0, screen_width, screen_height)];

  1. 弹出的链接替换在UIWebViewDelegate中,shouldStartLoadWithRequest方法里能够赢获得对应的NSU库罗德LRequest,举行管理,然后回来YES/NO;而在WKNavigationDelegate中,对应的办法应该是decidePolicyForNavigationAction,能够在navigationAction中取获得对应的request,然后实行拍卖,但是并未有重临值,而是利用回调方法开展处理。

  2. 初步键盘弹出在UIWebView中,有三个属性keyboardDisplayRequiresUserAction,设置为NO时就能够在页面刚加载时直接弹出键盘;在WKWebView中,是绝非这性情情的,若是要落实肖似的功用,就亟须替换WKWebView中相应的格局,代码如下:

    static void (*originalIMP)(id self, SEL _cmd, void* arg0, BOOL arg1, BOOL arg2, id arg3) = NULL;void interceptIMP (id self, SEL _cmd, void* arg0, BOOL arg1, BOOL arg2, id arg3) { originalIMP(self, _cmd, arg0, TRUE, arg2, arg3);}void setWkWebViewShowKeybord() { Class cls = NSClassFromString(@"WKContentView"); SEL originalSelector = NSSelectorFromString(@"_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:"); Method originalMethod = class_getInstanceMethod(cls, originalSelector); IMP impOvverride =  interceptIMP; originalIMP = method_getImplementation(originalMethod); method_setImplementation(originalMethod, impOvverride);}
    

    亟待调用�函数setWkWebViewShowKeybord,工夫够兑现该意义;须求特别注意的是,该函数只好调用叁次,不然会促成循环调用,程序崩溃。上述代码援用自stackoverflow的答案

  3. JavaScript的调用看起来和UIWebView的调用大致,三个方法是stringByEvaluatingJavaScriptFromString,另叁个是evaluateJavaScript,但实质上是一心不相同的,首要就在于叁个是联合调用,另七个是异步调用。借使原先的代码已经选拔了UIWebView,那么在退换WKWebView时应当要小心,因为异步调用是不得以况且调用八个js情势的,不然施行各类将无法保险。上面写出自个儿把异步调用更正为同步调用的不二等秘书籍,是促成在了WKWebViewcategory里面:

    - syncEvalJavascriptString:(NSString *)jsCode { __block id returnValue = nil; __block BOOL finished = NO; [self evaluateJavaScript:jsCode completionHandler:^(id _Nullable result, NSError * _Nullable error) { returnValue = result; finished = YES; }]; while (!finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } return returnValue;}
    

    亟需当心的正是NSRunLoop这里无法应用dispatch_semaphore_t非时限信号量代替,会造成永远等待的,已经实地度量过了。

_webView.scrollView.bounces = NO;

时下自身使用到的也就那几个了,后续借使有对于WKWebView的更加多询问的话,在追加吗。可是替换到了WKWebView之后,品质上着实提升了,比早前流畅多了。

_webView.navigationDelegate = self;//生命周期,调整页面跳转的代理,最常用

_webView.UIDelegate = self;//不常用

_webView.scrollView.scrollEnabled = NO;

[self.view addSubview:_webView];

2.加载页面

1)加载HTML:[_webView loadHTMLString:htmlString baseURL:nil];

2)加载NSURL:[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];

3)加载NSData : - (void)loadData:(NSData *)data MIMEType:(NSString

*)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL

*)baseURL;

3.代理方法

/*************追踪加载进度**********************/

#pragma mark - WKNavigationDelegate

// 页面开端加载时调用

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

[SVProgressHUD show];

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];

}

// 当内容开端回届时调用

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

}

// 页面加载成功未来调用

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

[SVProgressHUD dismiss];

}

// 页面加载退步时调用

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{

[SVProgressHUD dismiss];

本文由澳门新葡亰发布于计算机知识,转载请注明出处:WKWebView的使用(一)

关键词: 日记本 WKWebView

上一篇:逆向工程之当,安装与使用

下一篇:没有了

最火资讯