1. 程式人生 > >iOS WKWebView的使用

iOS WKWebView的使用

不能 控制 web prot 使用 minimum run and automatic

  項目中使用的是WKWebView,以下是從項目中抽取出來的,供想使用WKWebView的朋友們了解。

  可以直接修改代碼中的的控制器類名和類中的方法名,可更快速的拿到項目中使用。

(a) .h定義文件

  

#import <UIKit/UIKit.h>

@interface HZWebViewController : UIViewController

@end

 

(b) .m實現文件

#import "HZWebViewController.h"
#import <WebKit/WebKit.h>

@interface HZWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView *webView;

@end

@implementation HZWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 基本配置
    [self commonInit];

    // 加載Url(項目中的實際地址),這裏以"www.baidu.com"舉例
    NSString *urlString = @"www.baidu.com";
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:16.f];
    [self.webView loadRequest:request];
    
    // 註冊一個通知,以便可以處理相關業務,例如在優惠券頁面選中優惠券後可以傳遞給H5頁面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(valueTransmit:) name:@"SelectedCouponNotification" object:nil];

}

- (void)valueTransmit:(NSNotification *)notification {
    
    NSDictionary *dict = notification.userInfo;
    id object          = notification.object;
    
    /*
     
     // 優惠券頁面選中的優惠券數組(裏面包含的是是優惠券模型HZCouponModel)
     NSArray *couponArray = notification.object;
     
     // 模型數組->字典數組
     NSArray *dictArray = [HZCouponModel mj_keyValuesArrayWithObjectArray:couponArray];
     
     // 字典數組->Json,與H5之間是通過Json數據格式進行交互
     NSString *str = [dictArray toJSONString];
     
     // backOrderWeb 是H5定義好的方法
     NSString *js = [NSString stringWithFormat:@"backOrderWeb(%@)",str];

     */
    
    // js代碼中可以傳包含多個模型的數組等等
    NSString *js = @"";
    
    // App->H5 傳值
    [self.webView evaluateJavaScript:js completionHandler:^(id object, NSError *error) {
        if (error) {
            // 邏輯處理
        }else {
            NSLog(@"%@",error);
        }
    }];
}

- (void)commonInit {
    
    // 配置參數
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    
    // 設置偏好設置
    config.preferences = [[WKPreferences alloc]init];
    
    // 默認為0
    config.preferences.minimumFontSize = 10;
    
    // 默認認為YES
    config.preferences.javaScriptEnabled = YES;
    
    // 在iOS上默認為NO,表示不能自動通過窗口打開
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    
    // web內容處理池,由於沒有屬性可以設置,也沒有方法可以調用,不用手動創建
    config.processPool = [[WKProcessPool alloc]init];
    
    // 通過JS與webview內容交互
    config.userContentController = [[WKUserContentController alloc] init];
    
    // 註入JS對象名稱AppModel,當JS通過AppModel來調用時,
    // 我們可以在WKScriptMessageHandler代理中接收到
    // couponCallBack,orderIdCallBack,couponsJumpToPayDone 是與前端約定好的方法名稱
    [config.userContentController addScriptMessageHandler:self name:@"couponCallBack"];
    [config.userContentController addScriptMessageHandler:self name:@"orderIdCallBack"];
    [config.userContentController addScriptMessageHandler:self name:@"couponsJumpToPayDone"];
    
    WKWebView *webView                                = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    webView.backgroundColor                           = [UIColor clearColor];
    webView.opaque                                    = YES;
    webView.scrollView.showsVerticalScrollIndicator   = NO;
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    webView.navigationDelegate                        = self;
    webView.UIDelegate                                = self;
    self.webView                                      = webView;
    [self.view addSubview:webView];
}

#pragma mark - WKNavigationDelegate

/*
 * 在發送請求之前,決定是否跳轉
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *urlString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    
    if ([[urlString lastPathComponent] isEqualToString:@"openCoupon"]) {
        // 打開優惠券頁面
        decisionHandler(WKNavigationActionPolicyCancel);
    } else if ([[urlString lastPathComponent] isEqualToString:@"backProdutionDetail"]) {
        // 回到產品詳情
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

/*
 * 頁面加載完成之後調用
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"頁面加載完成");
}

/*
 * 頁面加載失敗時調用
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"頁面加載失敗");
}

/*
 * 當內容開始返回時調用
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

/*
 * 開始導航跳轉時會回調
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"來到這個方法");
}

/*
 * 執行JS代碼時會調用
 */
- (void)evaluateJavaScript:(NSString *)javaScriptString
         completionHandler:(void (^)(id, NSError *))completionHandler {
}

/*
 * H5->App 傳值
 * 註入JS對象名稱AppModel,當JS通過AppModel來調用時,
 * 在WKScriptMessageHandler代理中接收到
 */
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
    
    NSString *messageName = message.name;
    id messageBody        = message.body;
    
    // 可在以下對應語句中做邏輯處理,例如跳轉到對應的界面
    if ([messageName isEqualToString:@"couponCallBack"]) {
        
    }else if ([messageName isEqualToString:@"orderIdCallBack"]) {
        
    }else if ([messageName isEqualToString:@"couponsJumpToPayDone"]) {
        
    }
}

#pragma mark - WKUIDelegate

/**
 *  @author ChenCheng
 *
 *  web界面有彈出框時調用
 *
 *  @param webView           實現該代理的webview
 *  @param message           彈出框的內容
 *  @param frame             主窗口
 *  @param completionHandler 彈出框消失調用
 */
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (action) {
            completionHandler();
        }
    }];
    
    UIAlertController *alertController = [[UIAlertController alloc] init];
    [alertController addAction:action];
}

/**
 *  web界面中有彈出警告框時調用
 *
 *  @param webView           實現該代理的webview
 *  @param message           警告框中的內容
 *  @param frame             主窗口
 *  @param completionHandler 警告框消失調用
 */
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (action) {
            completionHandler(NO);
        }
    }];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (action) {
            completionHandler(YES);
        }
    }];
    
    UIAlertController *alertController = [[UIAlertController alloc] init];
    [alertController addAction:cancelAction];
    [alertController addAction:action];

}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
    
}

@end

  

iOS WKWebView的使用