OC與js交互二(WKWebView)

本文只是作爲筆記,更多的解釋看文末大神的解釋

html文本
<!DOCTYPE html>
    <html>
        <head>
            <title>iOS and Js</title>
            <style type="text/css">
                * {
                    font-size: 40px;
                }
            </style>
        </head>
        
        <body>
            
            <div style="margin-top: 100px">
                <br/>
                <div><input type="button" value="不帶參" onclick="buttomA()"></div>
                <br/>
                <div><input type="button" value="帶參" onclick="buttomB()"></div><br/>
            </div>

            <div id="SwiftDiv">
                <span id="jsParamFuncSpan" style="color: red; font-size: 50px;"></span>
            </div>
            
            <script type="text/javascript">
                function buttomA() {
                    window.webkit.messageHandlers.showSendMsg.postMessage(null);
                }
            
                function buttomB() {
                    window.webkit.messageHandlers.showParameterMsg.postMessage(['參數One', '參數Two']);
                }
            
                function getJsValue() {
                    return "js中傳遞出來的分享內容";
                }
            
            
            </script>
        </body>
    </html>
OC代碼
    #import "WKWebViewController.h"
    #import <WebKit/WebKit.h>


    #define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
    #define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
    #define NAV_HEIGHT [[UIApplication sharedApplication] statusBarFrame].size.height + self.navigationController.navigationBar.frame.size.height
    @interface WKWebViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate,WKScriptMessageHandler>
    @property (nonatomic, strong) WKWebView *wkwebView;
    @property (nonatomic, strong) CALayer *progresslayer;

    @end

    @implementation WKWebViewController

    - (CALayer *)progresslayer
    {
        if (!_progresslayer) {
            UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 3)];
            progress.backgroundColor = [UIColor clearColor];
            [self.view addSubview:progress];
            CALayer *layer = [CALayer layer];
            layer.frame = CGRectMake(0, 0, 0, 3);
            layer.backgroundColor = [UIColor orangeColor].CGColor;
            [progress.layer addSublayer:layer];
            self.progresslayer = layer;
        }
        return _progresslayer;
    }
    -(void)viewWillDisappear:(BOOL)animated{
        [super viewWillDisappear:animated];
        //避免引起循環引用,導致控制器無法被釋
        [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"showSendMsg"];
        [self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"showParameterMsg"];
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.title = @"WKWebView";
        [self configWkWebView];
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(0, 0, 35, 35);
        [rightBtn setTitle:@"分享" forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(shareBtnClick) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    }
    - (void )configWkWebView{
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        config.preferences = [[WKPreferences alloc] init];
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.userContentController = [[WKUserContentController alloc] init];
        config.processPool = [[WKProcessPool alloc] init];
        self.wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
        [self.wkwebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        self.wkwebView.UIDelegate = self;
        self.wkwebView.navigationDelegate =self;
        [self.view addSubview:self.wkwebView];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"html"];
        NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
        [self.wkwebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
        
        //js調OC 
        [config.userContentController addScriptMessageHandler:self name:@"showSendMsg"];
        [config.userContentController addScriptMessageHandler:self name:@"showParameterMsg"];
    }
    #pragma mark - WKScriptMessageHandler
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
        //js調OC
        if ([message.name isEqualToString:@"showSendMsg"]) {
            //不帶參按鈕點擊時間處理
            [self showMsg:@"不帶參"];
        }
        if ([message.name isEqualToString:@"showParameterMsg"]) {
            //帶參按鈕點擊時間處理
            NSString *showMsg = @"";
            NSArray *args = message.body;
            for (NSString *str in args) {
                NSLog(@"參數 ---- %@",str);
                if ([showMsg isEqualToString:@""]) {
                    showMsg = [NSString stringWithFormat:@"%@",str];
                }else{
                    showMsg = [NSString stringWithFormat:@"%@-%@",showMsg,str];
                }
            }
            [self showMsg:showMsg];
        }
    }
    - (void)showMsg:(NSString *)msg {
        [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
    }


    //進度條
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            self.progresslayer.opacity = 1;
            if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) {
                return;
            }
            self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
            if ([change[@"new"] floatValue] == 1) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.progresslayer.opacity = 0;
                });
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
                });
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    /**
     清理網頁緩存
     */
    - (void)deleteWebCache {
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
            NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                                            //WKWebsiteDataTypeOfflineWebApplicationCache,
                                                            WKWebsiteDataTypeMemoryCache,
                                                            //WKWebsiteDataTypeLocalStorage,
                                                            //WKWebsiteDataTypeCookies,
                                                            //WKWebsiteDataTypeSessionStorage,
                                                            //WKWebsiteDataTypeIndexedDBDatabases,
                                                            //WKWebsiteDataTypeWebSQLDatabases
                                                            ]];
            //// Date from
            NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
            //// Execute
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
                // Done
            }];
        } else {
            NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
            NSError *errors;
            [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        }
    }

    - (void)dealloc{
        [self deleteWebCache];
        [(WKWebView *)self.wkwebView removeObserver:self forKeyPath:@"estimatedProgress"];
    }




    #pragma mark -- OC調用js
    - (void)shareBtnClick{
        //如果方法裏需要傳參數,需要用 '' 套着
        [self.wkwebView evaluateJavaScript:@"getJsValue()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            //JS 返回結果
            NSLog(@"返回結果-%@ \n錯誤-%@",response,error);
            [self showMsg:[NSString stringWithFormat:@"JS中返回結果-%@",response]];
        }];
    }




    @end

下面這個老表對於OC與js交互有比較全面的一套解釋,從他的文章中可以學到很多👇
參考鏈接
Demo集合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章