精华内容
下载资源
问答
  • 文件操作和Wkwebview的使用
  • 使用WKWebView的一个带下载的web浏览界面
  • <p><strong>self</strong>.script = @"";  <strong>self</strong>.script = @"var xhr = new XMLHttpRequest();";  NSString* open =...请教大神门</p>
  • wkwebview加载本地沙盒文件wkwebview开发中一个很常见的问题,今天对该问题进行一个较为详细的记录1、#pragma mark -https认证//web项目里面,使用了https认证的问题- (void)webView:(WKWebView *)webView ...

    wkwebview加载本地沙盒文件是wkwebview开发中一个很常见的问题,今天对该问题进行一个较为详细的记录

    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、隐藏状态栏:

    NSString *phoneVersion = [[UIDevice currentDevice] systemVersion];

    NSArray *versionarr = [phoneVersion componentsSeparatedByString:@"."];

    if ([[versionarr objectAtIndex:0] integerValue]<11) {

    self.edgesForExtendedLayout = UIRectEdgeNone;

    }else{

    self.myweb.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//隐藏顶部状态栏,还要设置空间全屏

    }

    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是多大。官网是

    /! @abstract The minimum font size in points.

    @discussion The default value is 0.

    */

    5、弹出系统提示框:

    //web界面中有弹出警告框时调用

    - (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、加载远程网页:

    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、加载项目工程网页:

    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;//隐藏顶部状态栏,还要设置空间全屏

    self.mywebui.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//隐藏顶部状态栏,还要设置空间全屏

    }

    //点击web界面跳转时候执行的方法

    -(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;

    }

    // 在发送请求之前,决定是否跳转

    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    decisionHandler(WKNavigationActionPolicyAllow);

    return;

    }

    // 页面开始加载时调用

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

    // [MBProgressHUD showInView:self.view message:@"正在加载网页!!"];

    [self.activityIndiactorView startAnimating];

    NSLog(@"didStartProvisionalNavigation");

    }

    // 在收到响应后,决定是否跳转

    - (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;

    }

    // 当内容开始返回时调用

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

    self.responsecount = 0;

    NSLog(@"didCommitNavigation");

    }

    // 页面加载完成之后调用

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

    [self.activityIndiactorView stopAnimating];

    NSLog(@"didFinishNavigation");

    }

    // 页面加载失败时调用

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

    [self.activityIndiactorView stopAnimating];

    NSLog(@"didFailProvisionalNavigation");

    }

    // 接收到服务器跳转请求之后调用

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

    NSLog(@"didReceiveServerRedirectForProvisionalNavigation");

    NSLog(@"%s", __FUNCTION__);

    }

    3从接口下载压缩包,解压缩再加载出来。(本地沙盒目录指这几个:Library/Preferences、Library/Caches、Documents)

    //请求当前项目压缩包版本号。如果版本号比本地版本号大或者本地没有,请求zip压缩包;如果版本号和本地一样,直接加载本地web数据。

    -(void)getversion{

    [MBProgressHUD showInView:self.view indicatorMessage:@"正在加载网页版本数据" duration:-1];

    // 1.获得请求管理者

    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

    // 2.申明返回的结果是text/html类型

    mgr.responseSerializer = [ AFJSONResponseSerializer serializer];

    // 3.发送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:@"请求云端数据,请稍等" 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:@"请求云端数据,请稍等" 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:@"请求云端数据,请稍等" 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:@"本地网页版本不存在,请重启软件程序!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];

    [alert show];

    NSLog(@"error:%@",error);

    }];

    }

    #pragma mark 请求zip地址

    //请求到的压缩包数据,进行解压

    -(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) {

    //设置下载完成操作

    // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用

    NSString *htmlFilePath = [filePath path];// 将NSURL转成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:@"网页数据下载失败,请重启软件程序!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];

    [alert show];

    }];

    [downloadTask resume];

    }

    #pragma mark 解压

    //把压缩包数据解压到本地后,要想加载出来,必须把document数据复制到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:@"解压数据失败,请重启软件程序!" 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"];

    //第二步:创建加载URL和访问权限URL(加载URL:访问的初始文件一般是index;访问权限URL:所有html、js、资源文件所在的文件夹一般是项目文件名字)。注意如果没有访问权限URL,html没办法加载相关的js和资源文件。

    //创建加载URL方法一:

    // indexPath=[[NSURL fileURLWithPath:indexPath]absoluteString];

    // NSURL *loadurl =[NSURL URLWithString:indexPath];//URLWithString后面的path1必须前面有file:///,[[NSURL fileURLWithPath:path1]absoluteString]这个处理可以得到file:///

    //创建加载URL方法二:

    NSURL *loadurl =[NSURL fileURLWithPath:indexPath];//fileURLWithPath后面跟的是文件目录不需要file:///

    //创建访问权限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:@"网页加载成功!"];

    }else{

    [MBProgressHUD hideHUDForView:self.view];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"本地网页配置文件不存在,请重启软件程序!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];

    [alert show];

    }

    }

    注意:

    1、解压缩功能要导入SSZipArchive库(包含minizip和aes),导入后出现了20多个错误,解决办法:

    选择所有.c文件,将属性的 identity and type 改为Objective-C Source

    2、下载功能需要导入AFNetworking库。

    3、加载本地沙盒功能主要针对文件夹里面除了html还有js和其它资源文件,如果只有一个html文件,那accessURL就是loadURL。这里沙盒目录主要指:Library/Preferences、Library/Caches、Documents(建议使用Library/Caches)。

    1、引入工作:WebViewJavascriptBridge文件夹

    @property WKWebViewJavascriptBridge *webViewBridge;

    2、创建WebViewJavascriptBridge实例。

    _webViewBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];

    // 如果控制器里需要监听WKWebView 的`navigationDelegate`方法,就需要添加下面这行。

    [_webViewBridge setWebViewDelegate:self];

    3、iOS语法:web调用iOS的方法:

    [_webViewBridge registerHandler:@"locationClick" handler:^(id data, WVJBResponseCallback responseCallback) {

    NSDictionary *tempDic = data;

    NSLog(@"%@",tempDic);

    // 获取位置信息

    NSString *location = @"广东省深圳市南山区学府路XXXX号";

    // 将结果返回给js

    responseCallback(location);//responseCallback(nil);

    }];

    注意:

    (1)、js可以传数字给iOS,iOS通过[data isKindOfClass:[NSNumber class]]判断是不是数字类型

    (2)、iOS返回可以是数字类型如@1。

    (3)、无返回的情况

    js方法:

    WebViewJavascriptBridge.callHandler('colorClick',params);

    iOS方法:

    [_webViewBridge registerHandler:@"colorClick" handler:^(id data, WVJBResponseCallback responseCallback) {

    // data 的类型与 JS中传的参数有关

    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)、传入数字类型时候,如果用数字类型作为key去找[[NSUserDefaults standardUserDefaults] objectForKey:key],会导致崩溃。

    4、iOS语法:iOS调用web方法:

    * (1)、传字符串给js,所以如果是json或者array都需要转换成字符串传递。

    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执行方法

    * (2)、传数字给js。(传bool类型时候数字为0或者1就可以)

    NSString *jsStr = [NSString stringWithFormat:@"iOSCallJS(%@)",@0];

    [self.myweb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {}];//wkwebview执行方法

    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);

    }

    });

    }

    注意:调用安卓方法时候是顺序执行的,而调用iOS的时候顺序执行完成后,在回调到callHandler里面的。

    8、iOS11后web输入框键盘升起不回落问题

    @interface BaseWebViewVC ()

    /** 键盘谈起屏幕偏移量 */

    @property (nonatomic, assign) CGPoint keyBoardPoint;

    @end

    - (void)viewDidLoad {

    [super viewDidLoad];

    //增加键盘升起和降落监听通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    }

    #pragma mark - 键盘升起和降落通知监听方法,原生调用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、加载远程地址,地址网页内容更新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];

    }

    作为一个开发者,有一个学习的氛围和一个交流圈子特别重要,这是我的交流群(123),大家有兴趣可以进群里一起交流学习

    展开全文
  • WKWebView 播放下载的本地mp4文件

    千次阅读 2018-06-06 11:40:22
    WKWebView 播放下载的本地mp4文件WKWebView 使用video标签是可以通过使用相对位置或者使用绝对路径播放本地mp4文件的scr="/**.mp4" or scr="file:///*****"这里有两个问题1.视频文件是直接打包...

    WKWebView 播放下载的本地mp4文件

    WKWebView 使用video标签是可以通过使用相对位置或者使用绝对路径播放本地mp4文件的

    scr="/**.mp4" or scr="file:///*****"

    这里有两个问题

    1.视频文件是直接打包到APP内的

    在模拟器和真机上都可以使用上面的两种方式进行播放mp4文件


    2.视频是下载下来的,放到Document或者library目录下

    在模拟器里可以使用上面两种方式进行播放mp4文件,但是在真机上(iOS 8-11)是播放不了。此时需要将mp4文件拷贝一份到tmp目录下,然后使用tmp目录下的绝对路径进行播放。

    展开全文
  • #import "MSDSViewController.h"#import @interface MSDSViewController ()@property (nonatomic,strong) WKWebView*webView;@property (strong, nonatomic) UIProgressView*progressView;@end@implementationMSDSVi...

    #import "MSDSViewController.h"

    #import

    @interface MSDSViewController ()@property (nonatomic,strong) WKWebView*webView;

    @property (strong, nonatomic) UIProgressView*progressView;@end

    @implementationMSDSViewController- (void)viewDidLoad {

    [super viewDidLoad];

    self.view .backgroundColor= [MyController colorWithHexString:@"f4f7ff"];

    self.titleLabel.text=self.MSDSNmae; // 标题

    _webView= [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, Wwidth, Hheight- 64)];

    _webView.navigationDelegate=self;

    _webView .backgroundColor= [MyController colorWithHexString:@"f4f7ff"];

    [self.view addSubview:_webView];

    _progressView= [[UIProgressView alloc]initWithFrame:CGRectMake(0, 65, CGRectGetWidth(self.view.frame),2)];

    [self.view addSubview:_progressView];

    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

    [self createData];

    }- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{//NSLog(@" %s,change = %@",__FUNCTION__,change);

    if ([keyPath isEqual: @"estimatedProgress"] && object ==_webView) {

    [self.progressView setAlpha:1.0f];

    [self.progressView setProgress:_webView.estimatedProgress animated:YES];if(_webView.estimatedProgress >= 1.0f)

    {

    [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{

    [self.progressView setAlpha:0.0f];

    } completion:^(BOOL finished) {

    [self.progressView setProgress:0.0fanimated:NO];

    }];

    }

    }else{

    [super observeValueForKeyPath:keyPath ofObject:objectchange:change context:context];

    }

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

    NSLog(@"webViewDidStartLoad");

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

    NSLog(@"webViewDidFinishLoad");

    self.wuwangluo.hidden=YES;

    }- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{

    NSLog(@"webViewDidFail");

    }- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{

    NSLog(@"webViewDidFailProvisional");

    dispatch_async(dispatch_get_main_queue(),^{

    [MyController showAlert:@"网络连接异常,请检查网络"view:self.view];

    });

    self.wuwangluo.hidden=NO;

    [self.view bringSubviewToFront:self.wuwangluo];

    }- (void)createData{

    [self loadExamplePage:_webView];

    }- (void)loadExamplePage:(WKWebView*)webView {

    NSMutableURLRequest*request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.MSDSId]]; // 网络地址//NSString *path = [[NSBundle mainBundle] pathForResource:@"1111111" ofType:@"pdf"];//本地//NSURL *url = [NSURL fileURLWithPath:path];//NSURLRequest *request=[NSURLRequest requestWithURL:url];

    [_webView loadRequest:request];

    }- (void)dealloc {

    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];//if you have set either WKWebView delegate also set these to nil here

    [_webView setNavigationDelegate:nil];

    [_webView setUIDelegate:nil];

    }- (void) backBtnClicked {

    NSArray* types =@[WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeDiskCache];

    NSSet*websiteDataTypes =[NSSet setWithArray:types];

    NSDate*dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

    }];

    [self.navigationController popViewControllerAnimated:YES];

    }@end

    展开全文
  • 实现了WKWebView网络请求拦截,并下载静态资源文件,加载时优先通过本地资源文件进行加载
  • These days however they generally advise that developers use WKWebView instead of UIWebView as it's faster and offers significant JavaScript performance improvements. This is great, except that I can...

    UIWebView supports a whole list of file types, as detailed in this Apple Technical Q&A doc:

    In addition to HTML content, UIWebView can display specific document types.

    iPhone OS 2.2.1 supports the following document types:

    Excel (.xls)

    Keynote (.key.zip)

    Numbers (.numbers.zip)

    Pages (.pages.zip)

    PDF (.pdf)

    Powerpoint (.ppt)

    Word (.doc)

    iPhone OS 3.0 supports these additional document types:

    Rich Text Format (.rtf)

    Rich Text Format Directory (.rtfd.zip)

    Keynote '09 (.key)

    Numbers '09 (.numbers)

    Pages '09 (.pages)

    Which is great. These days however they generally advise that developers use WKWebView instead of UIWebView as it's faster and offers significant JavaScript performance improvements. This is great, except that I can't find a list of file types that are supported.

    It does appear to support media files (such as Quicktime .mov files) which UIWebView did not, but now Word documents (.docx) do not seem to work. Is there a list of file formats that are supported by WKWebView?

    解决方案

    I had the same question. I lodged a Technical Support Incident with Apple and received this answer (21st Sep 2017):

    All Microsoft Documents are supported.

    All iWork documents are supported.

    If UIWebView would render a document type then WKWebView will as well.

    On an iOS device running 10.3.3 and the Xcode 9.0 iOS 11.0 simulator, the above seems to work. I can display a range of MS Office documents (including docx, pptx, xlsx) as well as the UIWebView ones documented by Apple in QA 1630.

    The above list is however lacking at least the various image formats, so it's clearly incomplete. If I get more information from Apple I'll update this answer...

    (Bug report 17972625 requests WKWebView's documentation be updated to precisely specify what formats it does actually support, if you care to submit a duplicate to Apple Bug Reporter.)

    展开全文
  • iOS WKWebView加载本地文件之权威解说

    千次阅读 2018-10-18 10:58:42
      在实际的iOS开发中,我们有很多的地方需要通过WKWebView加载本地的文件。但是由于WKWebview存在着一些跨域的问题。UIWebView直接加载的方法不能正常使用了。这里就和大家分享一下常见的几种处理方法。 ...
  • 先简单介绍下我在工作中关于WKWebView的使用场景:1、首先是从后台获取到HTML富文本字符串内容,然后使用WKWebView加载出来2、将CSS样式文件下载到沙盒,以及将CSS样式文件预存到应用程序资源路径下,使用WKWebView...
  • WKWebView大家都很熟悉,iOS上加载HTML的利器! 但是有些情况我们并不仅仅需要加载在线的url网址,还可能用来加载本地的HTML文件或者HTML代码。 可就在iOS 14发布之后,我们发现无法加载本地HTML了!测试发现iOS 13...
  • 我有一个 WKWebView ,它会加载一个远程URL(html,js,css),然后加载应用程序中本地存储的mp4视频 . 问题是这些视频没有被加载 .该网站使用HTML 5视频标签,我通过与Javascript通信C#来设置本地网址 .视频路径是...
  • 主要介绍了iOS11 WKWebView 无法加载内容,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 本篇文章主要介绍了ios wkwebview离线化加载h5资源解决方案,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 无论是小游戏还是小程序,这些都需要加载更多的资源文件,处理更多的业务。这些都对网页加载的速度提出了较高的要求。UIWebView由于占用内存大,释放不掉一直备受诟病。而且目前是大多数的app支持的最低版本都是从...
  • WKWebView对网页和js,css,png等资源文件都进行缓存。...最佳解决方案是js中对每一个网址,js,css,png等资源文件下载地址都加版本号,这样既利用了WKWebView缓存机制又实现了他们按照需要刷新。...
  • 发现问题最近项目中使用到HTML5和原生的混合开发,项目在IOS10上面运行正常,在IOS8下遇到了兼容性的问题,HTML5页面可以加载出来,...使用Safari调试器查看HTML文件显示正常HTML文件显示正常截图但是JS文件和CSS...
  • 使用WKWebView加载3D模型,3D模型是使用webGL开发的,考虑到网络问题,采用本地化的方式,将3D模型数据下载到本地沙盒,将JS代码放入到工程目录下,再使用WKWebView加载index.html。 ### 问题一:WKWebView访问...
  • 可以设置很多的编码格式,下载软件打开CSS文件,发现文件的编码是 UTF-8无BOM格式 ,尝试转换为 UTF-8格式 的 文件的内容没有变化,但是使用16进制可以看到前面添加了3个字节的内容,这就是BOM头 ####问题的...
  • 需求想让点击'下载'的时候把图片下载到相册,查看web页发现,需要保存到相册的内容是PDF,不是图片,因为这个web页面是银行的,不是我们自己的,而且没法直接拿到这个PDF的下载地址进行文件下载; 想着就先把web页...
  • 这是我用来加载我的项目中的本地文件(iOS 10,Swift 3)的简化版本 . 根据评论中Raghuram和...我刚刚创建了一个全新的项目,这是文件夹结构:Update 19.04.2018: 添加了一个新功能,用HTML,CSS,JS文件下载.zip,在/...
  • 请到GITHUB下载最新:https://github.com/CoderJackyHuang/WKWebViewH5ObjCDemo 有专门的博文讲解如何使用:http://www.henishuo.com/wkwebview-js-h5-oc/ 喜欢就star吧! GIF过大,上传不了!只能截图,...
  • 这个功能已经写完快两个月了,马上要把这个H5功能改成原生的,也就是说之前的代码...主要是因为UIWebview和WKWebview的区别以及iOS的版本问题,因此需要兼容两种办法——iOS11.*以前和以后需求:在WKWebview的H5页面...
  • 测试提了这样的一个bug,就结合项目开始搜索相关资料终于找到...- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)...
  • WKWebView的缓存问题

    2021-06-13 08:50:52
    缓存策略WKWebView提供的实现了的缓存策略NSURLRequestUseProtocolCachePolicy//默认的缓存策略NSURLRequestReloadIgnoringCacheData//重新请求忽略缓存NSURLRequestReturnCacheDataElseLoad//有缓存就返回缓存,没有...
  • WKWebViewDemo.zip

    2020-04-15 18:45:47
    1. 利用iOS原生WKWebView打开 H5 游戏的同时将整个游戏所需的资源文件下载到本地沙盒目录下,便于第二次秒开(加载时优先通过本地资源文件进行加载) 2.此工程也可适用于打开 H5 商城,也可便于实现秒开 原理:在第...
  • WKWebView加载html图片过大,将图片缩放适配屏幕方法NSString *str = @"var script = document.createElement('script');""script.type = 'text/javascript';""script.text = \"function ResizeImages() { ""var ...
  • iOS WKWebView 拦截超链接

    千次阅读 2018-09-30 14:44:10
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { // 1.拦截请求 ...
  • 功能丰富的WKWebView

    2021-07-09 12:01:00
    支持`WKWebView`的复用,通过复用优化启动性能以及内存占用.7.支持各种自定义浏览器的`UserAgent`.8.支持拦截`WebView`的网络请求.9.支持操作`Cookie`.10.`demo`中提供了让业务`H5`页面秒开的方案(`HTML`模板渲染 &...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,257
精华内容 502
关键字:

wkwebview下载文件