wkwebview開發(fā)常見問題(wkwebview加載本地沙盒文件)

wkwebview加載本地沙盒文件是wkwebview開發(fā)中一個很常見的問題览爵,今天對該問題進行一個較為詳細的記錄

1麻敌、#pragma mark -https認證

//web項目里面诲宇,使用了https認證的問題
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

2孩革、隱藏狀態(tài)欄:

    NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSArray *versionarr = [phoneVersion componentsSeparatedByString:@"."];
    if ([[versionarr objectAtIndex:0] integerValue]<11) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }else{
        self.myweb.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//隱藏頂部狀態(tài)欄岁歉,還要設(shè)置空間全屏
    }

3、禁止WKWebView的手勢捏拉縮放

//推選這個方法膝蜈;這個方法在11.3.1和11.2.6都有效
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 禁止放大縮小
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
}

 //這個方法在11.3.1無效锅移。11.2.6有效
    self.myweb.scrollView.delegate = self;
//禁止手指捏合和放大
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}

4、我第一次合作是ionic寫的界面饱搏。
WKPreferences preferences = [WKPreferences new];
preferences.minimumFontSize = 40.0;
后來另外一個web工程師用vue寫的界面非剃。同樣的工程加載出來的界面,總是fontSize很大推沸。
我更改 preferences.minimumFontSize = 15.0;解決了這個問題备绽。minimumFontSize大致意思:web的一個px是多大。官網(wǎng)是
/
! @abstract The minimum font size in points.
@discussion The default value is 0.
*/
5鬓催、彈出系統(tǒng)提示框:

//web界面中有彈出警告框時調(diào)用
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

6肺素、三種加載html的方式:

  • 1、加載遠程網(wǎng)頁:
    NSString *urlstr = @"https://junction.dev.havensphere.com/static/086test1/r003/phone/index.html";
    NSURL *url =[NSURL URLWithString:urlstr];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [self.myweb loadRequest:request];
    [self.view addSubview:self.myweb];

  • 2宇驾、加載項目工程網(wǎng)頁:
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 15.0;
    configuration.preferences = preferences;

    self.myweb = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) configuration:configuration];
    self.myweb.navigationDelegate = self;
    self.myweb.UIDelegate = self;
    self.myweb.scrollView.delegate = self;
    self.myweb.scrollView.contentSize= CGSizeMake(Screen_Width, Screen_Height);
    self.myweb.scrollView.bounces = false;

    NSString *bundleFile = [[NSBundle mainBundle] pathForResource:@"HTML" ofType:@"bundle"];
    NSString *path = [bundleFile stringByAppendingString:@"/dist/index.html"];
    NSURL *fileURL = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [self.myweb loadRequest:request];
    [self.view addSubview:self.myweb];

    NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];
    NSArray *versionarr = [phoneVersion componentsSeparatedByString:@"."];
    if ([[versionarr objectAtIndex:0] integerValue]<11) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }else{
        self.myweb.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//隱藏頂部狀態(tài)欄倍靡,還要設(shè)置空間全屏
        self.mywebui.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//隱藏頂部狀態(tài)欄,還要設(shè)置空間全屏
    }    
//點擊web界面跳轉(zhuǎn)時候執(zhí)行的方法
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration");
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
// 在發(fā)送請求之前飞苇,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);
    return;
}
// 頁面開始加載時調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //    [MBProgressHUD showInView:self.view message:@"正在加載網(wǎng)頁>薄!"];
    [self.activityIndiactorView  startAnimating];
    NSLog(@"didStartProvisionalNavigation");
}
// 在收到響應(yīng)后布卡,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
    NSLog(@"decidePolicyForNavigationResponse");
    self.responsecount++;
    if (self.responsecount==7) {//處理加載時間很長的時候的加載問題
        [self.activityIndiactorView  stopAnimating];
    }
    return;
}

// 當內(nèi)容開始返回時調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    self.responsecount = 0;
    NSLog(@"didCommitNavigation");
}
// 頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.activityIndiactorView  stopAnimating];
    NSLog(@"didFinishNavigation");
}
// 頁面加載失敗時調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [self.activityIndiactorView  stopAnimating];
    NSLog(@"didFailProvisionalNavigation");
}
// 接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"didReceiveServerRedirectForProvisionalNavigation");
    NSLog(@"%s", __FUNCTION__);
}

  • 3從接口下載壓縮包雨让,解壓縮再加載出來。(本地沙盒目錄指這幾個:Library/Preferences忿等、Library/Caches栖忠、Documents
//請求當前項目壓縮包版本號。如果版本號比本地版本號大或者本地沒有贸街,請求zip壓縮包庵寞;如果版本號和本地一樣,直接加載本地web數(shù)據(jù)薛匪。
-(void)getversion{
    [MBProgressHUD showInView:self.view indicatorMessage:@"正在加載網(wǎng)頁版本數(shù)據(jù)" duration:-1];
    // 1.獲得請求管理者
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    // 2.申明返回的結(jié)果是text/html類型
    mgr.responseSerializer = [ AFJSONResponseSerializer serializer];
    // 3.發(fā)送GET請求
    [mgr GET:@"http://101.132.91.12:8681/iot/app/info?id=1" parameters:nil progress::^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%@",downloadProgress);
    }  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSString *version = [[[dic objectForKey:@"content"]objectAtIndex:0]objectForKey:@"versioncode"];
        NSString *defaultsversion = [[NSUserDefaults standardUserDefaults] objectForKey:@"versioncode"];
        self.defaultsversion = version;
        if (defaultsversion==nil) {
            [MBProgressHUD showInView:self.view indicatorMessage:@"請求云端數(shù)據(jù)捐川,請稍等" duration:-1];
            [self rquestZipArchivePath:@"http://101.132.91.12:8681/iot/file/app/iot.zip"];
            return ;
        }
        if ([version intValue]>[defaultsversion intValue]) {
            [MBProgressHUD showInView:self.view indicatorMessage:@"請求云端數(shù)據(jù),請稍等" duration:-1];
            [self rquestZipArchivePath:@"http://101.132.91.12:8681/iot/file/app/iot.zip"];
            return ;
        }
        NSArray *documentArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path1 = [[documentArray lastObject] stringByAppendingPathComponent:@"Preferences"];
        if([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/iot",path1]])
        {
            [self loadWebData];
        }else{
            [MBProgressHUD showInView:self.view indicatorMessage:@"請求云端數(shù)據(jù)逸尖,請稍等" duration:-1];
            [self rquestZipArchivePath:@"http://101.132.91.12:8681/iot/file/app/iot.zip"];
        }
        NSLog(@"responseObject:%@",version);
        return ;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"本地網(wǎng)頁版本不存在古沥,請重啟軟件程序瘸右!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [alert show];

        NSLog(@"error:%@",error);
    }];
}
#pragma mark 請求zip地址
//請求到的壓縮包數(shù)據(jù),進行解壓
-(void)rquestZipArchivePath:(NSString *)pathUrl{
    //遠程地址
    NSURL *URL = [NSURL URLWithString:pathUrl];
    //默認配置
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //請求
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    NSURLSessionDownloadTask * downloadTask= [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        //- block的返回值, 要求返回一個URL, 返回的這個URL就是文件的位置的路徑

        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        //再次之前先刪除本地文件夾里面相同的文件夾
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:cachesPath error:NULL];
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        NSString *extension = @"zip";
        while ((filename = [e nextObject])) {
            if ([[filename pathExtension] isEqualToString:extension]) {
                [fileManager removeItemAtPath:[cachesPath stringByAppendingPathComponent:filename] error:NULL];
            }
        }
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        if (error==nil) {
            //設(shè)置下載完成操作
            // filePath就是你下載文件的位置岩齿,你可以解壓太颤,也可以直接拿來使用
            NSString *htmlFilePath = [filePath path];// 將NSURL轉(zhuǎn)成NSString
            NSArray *documentArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
            NSString *path = [[documentArray lastObject] stringByAppendingPathComponent:@"Preferences/"];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/iot",path] error:nil];
            [self releaseZipFilesWithUnzipFileAtPath:htmlFilePath Destination:path];
            return ;
        }
        [MBProgressHUD hideHUDForView:self.view];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"網(wǎng)頁數(shù)據(jù)下載失敗,請重啟軟件程序盹沈!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [alert show];
    }];
    [downloadTask resume];
}
#pragma mark 解壓
//把壓縮包數(shù)據(jù)解壓到本地后龄章,要想加載出來,必須把document數(shù)據(jù)復制到Preferences文件夾
- (void)releaseZipFilesWithUnzipFileAtPath:(NSString *)zipPath Destination:(NSString *)unzipPath{
    NSError *error;
    if ([SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath overwrite:YES password:nil error:&error delegate:self]) {

        NSString *path = [unzipPath stringByAppendingString:@"/iot"];
        NSFileManager *fileManager1 = [NSFileManager defaultManager];
        NSString *tmpPath2 = NSTemporaryDirectory();
        if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@iot",tmpPath2]]){
            [fileManager1 removeItemAtPath:[NSString stringWithFormat:@"%@iot",tmpPath2] error:nil];
        }
        [fileManager1 copyItemAtPath:[NSString stringWithFormat:@"%@/iot",path] toPath:[NSString stringWithFormat:@"%@iot",tmpPath2] error:nil];
        [[NSUserDefaults standardUserDefaults] setObject:self.defaultsversion forKey:@"versioncode"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self loadWebData];
//        NSLog(@"解壓縮成功乞封!");
    }
    else{
        [MBProgressHUD hideHUDForView:self.view];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"解壓數(shù)據(jù)失敗做裙,請重啟軟件程序!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [alert show];
    }
}
//加載本地沙盒目錄下的index.html(本地沙盒目錄指這幾個:Library/Preferences肃晚、Library/Caches菇用、Documents)
-(void)loadWebData{
    NSArray *documentArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path1 = [[documentArray lastObject] stringByAppendingPathComponent:@"Preferences"];
    NSFileManager *fileManager1 = [NSFileManager defaultManager];
    if([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/iot",path1]])
    {
    //第一步:找到文件所在目錄
        NSArray *LibraryArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *CachesPath = [[LibraryArray lastObject] stringByAppendingPathComponent:@"Caches"];
        NSString *indexPath = [CachesPath stringByAppendingPathComponent:@"/dist/index.html"];
        //第二步:創(chuàng)建加載URL和訪問權(quán)限URL(加載URL:訪問的初始文件一般是index;訪問權(quán)限URL:所有html陷揪、js、資源文件所在的文件夾一般是項目文件名字)杂穷。注意如果沒有訪問權(quán)限URL悍缠,html沒辦法加載相關(guān)的js和資源文件。
        //創(chuàng)建加載URL方法一:
    //    indexPath=[[NSURL fileURLWithPath:indexPath]absoluteString];
    //    NSURL *loadurl =[NSURL URLWithString:indexPath];//URLWithString后面的path1必須前面有file:///,[[NSURL fileURLWithPath:path1]absoluteString]這個處理可以得到file:///
        //創(chuàng)建加載URL方法二:
        NSURL *loadurl =[NSURL fileURLWithPath:indexPath];//fileURLWithPath后面跟的是文件目錄不需要file:///
        //創(chuàng)建訪問權(quán)限URL
        NSString *accessURLStr = [[[LibraryArray lastObject] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"/dist"];
        NSURL *accessURL = [NSURL fileURLWithPath:accessURLStr];
        //第三步:進行加載
        [self.myweb loadFileURL:loadurl allowingReadAccessToURL:accessURL];
        [MBProgressHUD showInView:self.view successMessage:@"網(wǎng)頁加載成功耐量!"];
    }else{
        [MBProgressHUD hideHUDForView:self.view];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"本地網(wǎng)頁配置文件不存在飞蚓,請重啟軟件程序!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [alert show];
    }
}

注意:
1廊蜒、解壓縮功能要導入SSZipArchive庫(包含minizip和aes)趴拧,導入后出現(xiàn)了20多個錯誤,解決辦法:
選擇所有.c文件山叮,將屬性的 identity and type 改為Objective-C Source
2著榴、下載功能需要導入AFNetworking庫。
3屁倔、加載本地沙盒功能主要針對文件夾里面除了html還有js和其它資源文件脑又,如果只有一個html文件,那accessURL就是loadURL锐借。這里沙盒目錄主要指:Library/Preferences问麸、Library/Caches、Documents(建議使用Library/Caches)钞翔。

7严卖、js和原生交互:
參考文章:iOS下JS與OC互相調(diào)用(六)--WKWebView + WebViewJavascriptBridge

1、引入工作:WebViewJavascriptBridge文件夾
@property WKWebViewJavascriptBridge *webViewBridge;
2布轿、創(chuàng)建WebViewJavascriptBridge實例哮笆。
    _webViewBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];
// 如果控制器里需要監(jiān)聽WKWebView 的`navigationDelegate`方法来颤,就需要添加下面這行。
[_webViewBridge setWebViewDelegate:self];
3疟呐、iOS語法:web調(diào)用iOS的方法:
    [_webViewBridge registerHandler:@"locationClick" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *tempDic = data;
        NSLog(@"%@",tempDic);
        // 獲取位置信息
        NSString *location = @"廣東省深圳市南山區(qū)學府路XXXX號";
        // 將結(jié)果返回給js        
        responseCallback(location);//responseCallback(nil);
    }];
注意:
(1)脚曾、js可以傳數(shù)字給iOS,iOS通過[data isKindOfClass:[NSNumber class]]判斷是不是數(shù)字類型
(2)启具、iOS返回可以是數(shù)字類型如@1本讥。
(3)、無返回的情況
js方法:
 WebViewJavascriptBridge.callHandler('colorClick',params);
iOS方法:
 [_webViewBridge registerHandler:@"colorClick" handler:^(id data, WVJBResponseCallback responseCallback) {
 // data 的類型與 JS中傳的參數(shù)有關(guān)
 NSDictionary *tempDic = data;

 CGFloat r = [[tempDic objectForKey:@"r"] floatValue];
 CGFloat g = [[tempDic objectForKey:@"g"] floatValue];
 CGFloat b = [[tempDic objectForKey:@"b"] floatValue];
 CGFloat a = [[tempDic objectForKey:@"a"] floatValue];

 weakSelf.webView.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
 }];
(4)鲁冯、傳入數(shù)字類型時候拷沸,如果用數(shù)字類型作為key去找[[NSUserDefaults standardUserDefaults] objectForKey:key],會導致崩潰薯演。
4撞芍、iOS語法:iOS調(diào)用web方法:
* (1)、傳字符串給js跨扮,所以如果是json或者array都需要轉(zhuǎn)換成字符串傳遞序无。
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSData *jsonData= [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsStr = [NSString stringWithFormat:@"backMQTTData('%@')",jsonString];
    [self.myweb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];//wkwebview執(zhí)行方法
* (2)、傳數(shù)字給js衡创。(傳bool類型時候數(shù)字為0或者1就可以)
        NSString *jsStr = [NSString stringWithFormat:@"iOSCallJS(%@)",@0];
        [self.myweb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];//wkwebview執(zhí)行方法
                alert(typeof(istrue));//number
                alert(istrue);
5帝嗡、js語法:
 if (window.AndroidWebView) {

  }else if(window.WebViewJavascriptBridge){
         WebViewJavascriptBridge.callHandler(funName,iosKey,function(response) {
            if(methodType==APPCONFIG.METHOD_GET){
                callback(response);
            }
         });
    }
注意:調(diào)用安卓方法時候是順序執(zhí)行的,而調(diào)用iOS的時候順序執(zhí)行完成后璃氢,在回調(diào)到callHandler里面的哟玷。

8、iOS11后web輸入框鍵盤升起不回落問題

@interface BaseWebViewVC ()<WKUIDelegate,WKNavigationDelegate>
/** 鍵盤談起屏幕偏移量 */
@property (nonatomic, assign) CGPoint keyBoardPoint;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    //增加鍵盤升起和降落監(jiān)聽通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - 鍵盤升起和降落通知監(jiān)聽方法一也,原生調(diào)用js方法放回給js
- (void) keyboardWillShow : (NSNotification*)notification {
    NSLog(@"keyboardWillShow");
    CGPoint point = self.myweb.scrollView.contentOffset;
    self.keyBoardPoint = point;
}
- (void) keyboardWillHide : (NSNotification*)notification {
    NSLog(@"keyboardWillHide");
    self.myweb.scrollView.contentOffset = self.keyBoardPoint;    
}

9巢寡、加載遠程地址,地址網(wǎng)頁內(nèi)容更新iOS不更新問題

-(void)initRemoteWebViewWithUrl:(NSString *)urlStr{
    __block NSString *urlblock = urlStr;
    NSURL *url =[NSURL URLWithString:urlStr];
    NSURLRequest *request;
    NSArray *usercache = [[NSUserDefaults standardUserDefaults] objectForKey:urlblock];
    NSLog(@"web:獲取緩存更新日期:%@",usercache);
    if (usercache==nil) {
        NSLog(@"web:沒有緩存更新日期");
        request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    }else if ([usercache[0] isEqualToString:usercache[1]]){
        NSLog(@"web:緩存更新日期一致");
        request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    }else{
        NSLog(@"web:緩存更新日期不一致");
        request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    }
    [self.myweb loadRequest:request];
    request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"httpResponse == %@", httpResponse);
        if (httpResponse==nil) {
            NSLog(@"web:httpResponse為空");
        }else{
            NSString *lastModified = [httpResponse.allHeaderFields objectForKey:@"Last-Modified"];
            if (!(lastModified==nil||lastModified.length==0)) {
                NSArray *usercacheblock = [[NSUserDefaults standardUserDefaults] objectForKey:urlblock];
                NSArray *userobject;
                if (usercacheblock==nil||usercacheblock.count==0) {
                    userobject = [[NSArray alloc] initWithObjects:lastModified,lastModified, nil];
                }else{
                    userobject = [[NSArray alloc] initWithObjects:usercacheblock[1],lastModified, nil];
                }
                NSLog(@"web:存儲緩存更新日期:%@",userobject);
                [[NSUserDefaults standardUserDefaults] setObject:userobject forKey:urlblock];
            }
        }
    }] resume];
}

作為一個開發(fā)者椰苟,有一個學習的氛圍和一個交流圈子特別重要抑月,這是我的交流群(123),大家有興趣可以進群里一起交流學習

原文地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末尊剔,一起剝皮案震驚了整個濱河市爪幻,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌须误,老刑警劉巖挨稿,帶你破解...
    沈念sama閱讀 211,376評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異京痢,居然都是意外死亡奶甘,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評論 2 385
  • 文/潘曉璐 我一進店門祭椰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來臭家,“玉大人疲陕,你說我怎么就攤上這事《ち蓿” “怎么了蹄殃?”我有些...
    開封第一講書人閱讀 156,966評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長你踩。 經(jīng)常有香客問我诅岩,道長,這世上最難降的妖魔是什么带膜? 我笑而不...
    開封第一講書人閱讀 56,432評論 1 283
  • 正文 為了忘掉前任吩谦,我火速辦了婚禮,結(jié)果婚禮上膝藕,老公的妹妹穿的比我還像新娘式廷。我一直安慰自己,他們只是感情好芭挽,可當我...
    茶點故事閱讀 65,519評論 6 385
  • 文/花漫 我一把揭開白布滑废。 她就那樣靜靜地躺著,像睡著了一般袜爪。 火紅的嫁衣襯著肌膚如雪策严。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,792評論 1 290
  • 那天饿敲,我揣著相機與錄音,去河邊找鬼逛绵。 笑死怀各,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的术浪。 我是一名探鬼主播瓢对,決...
    沈念sama閱讀 38,933評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼胰苏!你這毒婦竟也來了硕蛹?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,701評論 0 266
  • 序言:老撾萬榮一對情侶失蹤硕并,失蹤者是張志新(化名)和其女友劉穎法焰,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體倔毙,經(jīng)...
    沈念sama閱讀 44,143評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡埃仪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,488評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了陕赃。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片卵蛉。...
    茶點故事閱讀 38,626評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡颁股,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出傻丝,到底是詐尸還是另有隱情甘有,我是刑警寧澤,帶...
    沈念sama閱讀 34,292評論 4 329
  • 正文 年R本政府宣布葡缰,位于F島的核電站亏掀,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏运准。R本人自食惡果不足惜幌氮,卻給世界環(huán)境...
    茶點故事閱讀 39,896評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胁澳。 院中可真熱鬧该互,春花似錦、人聲如沸韭畸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽胰丁。三九已至随橘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锦庸,已是汗流浹背机蔗。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留甘萧,地道東北人萝嘁。 一個月前我還...
    沈念sama閱讀 46,324評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像扬卷,于是被迫代替她去往敵國和親牙言。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,494評論 2 348