• ios开发webview 的三种引用方式以及动态更新本地静态页的方法


    1最简单最基本的

        NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        [self.webView loadRequest:request];

    2  引用 导入工程的文件   记得放入对应的js   css 文件

        NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"mall" ofType:@"html"];

        NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];    // 获取当前应用的根目录

        NSString *path = [[NSBundle mainBundle] bundlePath];

        NSURL *baseURL = [NSURL fileURLWithPath:path];  // 通过baseURL的方式加载的HTML

        // 可以在HTML内通过相对目录的方式加载js,css,img等文件

        [self.webView loadHTMLString:htmlCont baseURL:baseURL];

    3 引用沙盒里的文件(文件需要下载到沙盒里,后续会整理相关代码)

        NSArray  *paths  =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

        NSString *docDir = [paths objectAtIndex:0];

        NSString *filePath = [docDir stringByAppendingPathComponent:@"mall.html"];

        NSURL *baseUrl = [NSURL URLWithString:filePath];

        NSString *htmlstring=[[NSString alloc]initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil];

        [self.webView loadHTMLString:htmlstring baseURL:baseUrl];

    4 更新本地静态页

    //

    //  ViewController.m

    //  VueText

    //

    //  Created by dongqiangfei on 2017/3/22.

    //  Copyright © 2017年 dongqiangfei. All rights reserved.

    //

    #import "ViewController.h"

    #import "WebViewController.h"

    #import "AFNetworking.h"

    #import "ZipArchive.h"

    #define WIDTHWSCREEN [UIScreen mainScreen].bounds.size.width

    @interface ViewController ()

    {

        UILabel *slider_lab;

    }

    @end

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        [self make_btn];

        [self make_slider];

        

        //获取文件路径

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录

        NSLog(@"NSDocumentDirectory:%@",documentsDirectory);

        // Do any additional setup after loading the view, typically from a nib.

    }

    -(void)make_slider

    {

        slider_lab = [[UILabel alloc] initWithFrame:CGRectMake(WIDTHWSCREEN/2-100, 50, 200, 30)];

        slider_lab.textColor = [UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1];

        slider_lab.textAlignment = NSTextAlignmentCenter;

        [self.view addSubview:slider_lab];

    }

    -(void)make_btn

    {

        NSArray *arr = @[@"查看效果",@"下载文件_更新成功",@"删除文件",@"解压文件",@"下载原始文件",@"Vue更新单个文件",@"Vue本地框架更新文件"];

        

        for (int i=0 ; i< arr.count; i++) {

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

        btn.frame = CGRectMake(WIDTHWSCREEN/2-100, 200+50*i, 200, 30);

        [btn setTitle:arr[i] forState:UIControlStateNormal];

            btn.tag = 1000 +i;

        [btn addTarget:self action:@selector(btn_click:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:btn];

            }

    }

    -(void)btn_click:(UIButton *)btn

    {

        // 原始链接

        NSString *orange_str = @"连接可以上传文件到博客园获得";

        

        //更新成功的连接  更新所有的文件

        NSString *success_update = @"连接可以上传文件到博客园获得";

        

        //更新单个文件

        NSString *mall_single_update = @"连接可以上传文件到博客园获得";

        

        //更新单个文件 以及更新某个文件夹里的文件 以及使用本地vue框架

        NSString *mall_single_locatial_update = @"连接可以上传文件到博客园获得";

        

        if (btn.tag == 1000) {//查看效果

            WebViewController *vc = [[WebViewController alloc] init];

            [self presentViewController:vc animated:YES completion:nil];

        }else if (btn.tag == 1001){//afn下载文件

            [self download_file_with_file_name:@"html.zip" and_url_string:success_update];

        }else if (btn.tag == 1002){//删除文件

            [self deleteFile:@"c下载"];

        }else if (btn.tag == 1003){//解压文件

            [self UnZipWith:@"html.zip"];

        }else if (btn.tag == 1004){//c 函数下载

            [self download_file_with_file_name:@"html.zip" and_url_string:orange_str];

           //NSString *str_name = [self DownloadTextFile:orange_str fileName:@"html.zip"];

           // NSLog(@"%@",str_name);

        }else if (btn.tag == 1005){//单独更新一个页面   用上vue

            [self download_file_with_file_name:@"html.zip" and_url_string:mall_single_update];

        }else if (btn.tag == 1006){//更新单个文件 以及更新某个文件夹里的文件 以及使用本地vue框架

            [self download_file_with_file_name:@"html.zip" and_url_string:mall_single_locatial_update];

        }

    }

    // 删除沙盒里的文件

    -(void)deleteFile:(NSString *)file {

        NSFileManager* fileManager=[NSFileManager defaultManager];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

        //文件名

        NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:file];

        BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];

        if (!blHave) {

            NSLog(@"no  have");

            return ;

        }else {

            NSLog(@" have");

            BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];

            if (blDele) {

                slider_lab.text = @"删除下载文件解压完毕的文件";

                slider_lab.text = @"可以去看效果喽";

                NSLog(@"dele success");

            }else {

                slider_lab.text = @"删除下载文件解压完毕的文件失败";

                NSLog(@"dele fail");

            }

        }

    }

    - (void)OpenZip:(NSString*)zipPath  unzipto:(NSString*)_unzipto

    {

        ZipArchive* zip = [[ZipArchive alloc] init];

        if( [zip UnzipOpenFile:zipPath] )

        {

            BOOL ret = [zip UnzipFileTo:_unzipto overWrite:YES];

            if( NO==ret )

            {

                NSLog(@"error");

            }

            [zip UnzipCloseFile];

            slider_lab.text = @"解压下载文件成功";

            

            //删除无用文件

            [self deleteFile:@"__MACOSX"];

            [self deleteFile:@"html.zip"];

            

        }

    }

    /**解压缩文件 str_name 解压出来的文件命名**/

    -(void)UnZipWith:(NSString *)str_name

    {

        slider_lab.text = @"开始解压下载文件";

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录

        NSLog(@"NSDocumentDirectory:%@",documentsDirectory);

        [self OpenZip:[NSString stringWithFormat:@"%@/%@",documentsDirectory,str_name] unzipto:documentsDirectory];

    }

    //c 函数下载文件

    -(NSString*)DownloadTextFile:(NSString*)fileUrl  fileName:(NSString*)_fileName

    {

        NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);//使用C函数NSSearchPathForDirectoriesInDomains来获得沙盒中目录的全路径。

        NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

    //    NSString *sandboxPath = NSHomeDirectory();

    //    NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"TestDownImgZip.app"];//将Documents添加到sandbox路径上//TestDownImgZip.app

        NSString *FileName=[ourDocumentPath stringByAppendingPathComponent:_fileName];//fileName就是保存文件的文件名

        NSFileManager *fileManager = [NSFileManager defaultManager];

        // Copy the database sql file from the resourcepath to the documentpath

        if ([fileManager fileExistsAtPath:FileName])

        {

            return FileName;

        }else

        {

            NSURL *url = [NSURL URLWithString:fileUrl];

            NSData *data = [NSData dataWithContentsOfURL:url];

            [data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName

        }

        return FileName;

    }

    //下载文件  afn

    - (void)download_file_with_file_name:(NSString *)file_name and_url_string:(NSString *)url_name{

        slider_lab.text = @"开始下载文件";

        NSString *savedPath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",file_name]];

        //    NSDictionary *paramaterDic= @{@"jsonString":[@{@"userid":@"2332"} JSONString]?:@""};

        [self downloadFileWithOption:@{}

                       withInferface:url_name

                           savedPath:savedPath

                     downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

                         

                     } downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {

                         

                     } progress:^(float progress) {

                         

                     }];

    }

    /**

     *  @author Jakey

     *

     *  @brief  下载文件

     *

     *  @param paramDic   附加post参数

     *  @param requestURL 请求地址

     *  @param savedPath  保存 在磁盘的位置

     *  @param success    下载成功回调

     *  @param failure    下载失败回调

     *  @param progress   实时下载进度回调

     */

    - (void)downloadFileWithOption:(NSDictionary *)paramDic

                     withInferface:(NSString*)requestURL

                         savedPath:(NSString*)savedPath

                   downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

                   downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

                          progress:(void (^)(float progress))progress

    {

        

        //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];

        AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

        NSMutableURLRequest *request =[serializer requestWithMethod:@"GET" URLString:requestURL parameters:paramDic error:nil];

        

        //以下是手动创建request方法 AFQueryStringFromParametersWithEncoding有时候会保存

        //    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]];

        //   NSMutableURLRequest *request =[[[AFHTTPRequestOperationManager manager]requestSerializer]requestWithMethod:@"POST" URLString:requestURL parameters:paramaterDic error:nil];

        //

        //    NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

        //

        //    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];

        //    [request setHTTPMethod:@"POST"];

        //

        //    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(paramaterDic, NSASCIIStringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];

        

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];

        [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];

        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

            float p = (float)totalBytesRead / totalBytesExpectedToRead;

            progress(p);

            NSLog(@"download:%f", (float)totalBytesRead / totalBytesExpectedToRead);

            slider_lab.text = [NSString stringWithFormat:@"下载进度:%0.2f%@",(float)(100.0*totalBytesRead / totalBytesExpectedToRead),@"%"];

        }];

        

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            success(operation,responseObject);

            slider_lab.text = @"下载成功";

            NSLog(@"下载成功");

            [self UnZipWith:@"html.zip"];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            success(operation,error);

            slider_lab.text = @"下载失败";

            NSLog(@"下载失败");

        }];

        

        [operation start];

    }

    -(void)receive_lujing

    {

        NSString *path = NSHomeDirectory();//主目录

        NSLog(@"NSHomeDirectory:%@",path);

        NSString *userName = NSUserName();//与上面相同

        NSString *rootPath = NSHomeDirectoryForUser(userName);

        NSLog(@"NSHomeDirectoryForUser:%@",rootPath);

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录

        NSLog(@"NSDocumentDirectory:%@",documentsDirectory);

    }

    - (void)didReceiveMemoryWarning {

        [super didReceiveMemoryWarning];

        // Dispose of any resources that can be recreated.

    }

    @end

    以下是js传参的方法

    - (void)webViewDidFinishLoad:(UIWebView *)webView {

        NSString *colorString = @"color";

        NSString *getValue = [NSString stringWithFormat:@"javascript:js方法('%@','%@','%@','%@','%@','%@')",[BDSingleton sharedSingle].username,[BDSingleton sharedSingle].token,thisGroupid,kBaseWebViewLocationURL,conditionStr,colorString];

        [webView stringByEvaluatingJavaScriptFromString:getValue];

    }

  • 相关阅读:
    junit源码解析--测试驱动运行阶段
    junit源码解析--初始化阶段
    junit源码解析--核心类
    junit测试套件
    junit参数化测试
    junit忽略测试方法
    Junit4常用注解
    泛型技术
    在使用Java8并行流时的问题分析
    Linux 常用性能分析命令
  • 原文地址:https://www.cnblogs.com/godlovexq/p/6802114.html
Copyright © 2020-2023  润新知