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

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM