iOS下载zip 解压 加载其中的html(附带搭建简易本地测试服务器)

1、有远程zip下载链接的可以跳过这一步(搭建本地简易服务器)

简书链接:https://www.jianshu.com/p/ad0833f4845a

2、 做前期准备  导入需要的库文件  

   1) AFNetworking 和SSZipArchive(一个加载库 一个解压库 )

podfile:

platform :ios,'8.0'

target 'your  project name' do

pod 'AFNetworking'

pod 'SSZipArchive'

end

没有pods 的看这里 cocoapods安装以及使用 https://www.jianshu.com/p/6e71fbeb71b7

3、上代码

1)@property(nonatomic,copy)NSString * urlstr;

@property(nonatomic,copy)NSString * decodestr;

@property(nonatomic,strong)WKWebView * webView;

下载zip代码 

-(void)rquestZipArchivePath:(NSString*)pathUrl andHtmlVersion:(NSString*)version{

    //远程地址

    NSURL*URL = [NSURLURLWithString:pathUrl];

    //默认配置

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    //请求

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];


    NSURLSessionDownloadTask* downloadTask =[managerdownloadTaskWithRequest:requestprogress:^(NSProgress*_NonnulldownloadProgress) {


        doublecurr=(double)downloadProgress.completedUnitCount;

        doubletotal=(double)downloadProgress.totalUnitCount;

        NSLog(@"下载进度==%.2f",curr/total);

    }destination:^NSURL*_Nonnull(NSURL*_NonnulltargetPath,NSURLResponse*_Nonnullresponse) {

        //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径


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


        //再次之前先删除本地文件夹里面相同的文件夹

        NSFileManager*fileManager = [NSFileManagerdefaultManager];

        NSArray*contents = [fileManagercontentsOfDirectoryAtPath:cachesPatherror:NULL];

        NSEnumerator*e = [contentsobjectEnumerator];

        NSString*filename;

        NSString*extension =@"zip";

        while((filename = [enextObject])) {


            if([[filenamepathExtension]isEqualToString:extension]) {


                [fileManagerremoveItemAtPath:[cachesPathstringByAppendingPathComponent:filename]error:NULL];

            }

        }

        NSString*path = [cachesPathstringByAppendingPathComponent:response.suggestedFilename];

        return[NSURLfileURLWithPath:path];

    }completionHandler:^(NSURLResponse*_Nonnullresponse,NSURL*_NullablefilePath,NSError*_Nullableerror) {

        //设置下载完成操作


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

        NSString*htmlFilePath = [filePathpath];// 将NSURL转成NSString

        NSArray*documentArray =  NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

        NSString *path = [[documentArray lastObject] stringByAppendingPathComponent:@"Preferences"];


        NSFileManager*fileManager = [NSFileManagerdefaultManager];

        [fileManagerremoveItemAtPath:[NSString stringWithFormat:@"%@/html",path] error:nil];

        self.urlstr=htmlFilePath;

        self.decodestr=path;

    }];

    [downloadTaskresume];

}

解压代码

- (void)releaseZipFilesWithUnzipFileAtPath:(NSString*)zipPath Destination:(NSString*)unzipPath{

    //    NSLog(@"%@,%@",zipPath,unzipPath);

    NSError*error;

    if ([SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath overwrite:YES password:nil error:&error delegate:self]) {

        NSLog(@"success");

    }

    else{

        NSLog(@"%@",error);

    }

  // 压缩包的全路径(包括文件名)

//    NSString *destinationPath = zipPath;

    // 目标路径,

    NSString*destinationPath = unzipPath;

    // 解压, 返回值代表是否解压完成

    Booleanb= [SSZipArchiveunzipFileAtPath:zipPathtoDestination:destinationPath];


//    ------------ 带回调的解压    ------------

    Booleanb1 = [SSZipArchiveunzipFileAtPath:zipPathtoDestination:destinationPathprogressHandler:^(NSString*_Nonnullentry,unz_file_infozipInfo,longentryNumber,longtotal) {

        // entry : 解压出来的文件名

        //entryNumber : 第几个, 从1开始

        //total : 总共几个

        NSLog(@"progressHandler:%@, entryNumber:%ld, total:%ld  names:%@", entry, entryNumber, total,destinationPath);

    }completionHandler:^(NSString*_Nonnullpath,BOOLsucceeded,NSError*_Nullableerror) {

        //path : 被解压的压缩吧全路径

        //succeeded 是否成功

        // error 错误信息

        NSLog(@"completionHandler:%@, , succeeded:%d, error:%@", path, succeeded, error);

    }];

}

#pragma mark - SSZipArchiveDelegate

- (void)zipArchiveWillUnzipArchiveAtPath:(NSString*)path zipInfo:(unz_global_info)zipInfo {

    NSLog(@"将要解压%d",zipInfo.number_entry);


}

- (void)zipArchiveDidUnzipArchiveAtPath:(NSString*)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString*)unzippedPat uniqueId:(NSString*)uniqueId {

    NSLog(@"解压完成!");

}

展示加载zip中的网页

//    /初始化一个WKWebViewConfiguration对象

    WKWebViewConfiguration *config = [WKWebViewConfiguration new];

    //初始化偏好设置属性:preferences

    config.preferences = [WKPreferences new];

    //The minimum font size in points default is 0;

    config.preferences.minimumFontSize = 10;

    //是否支持JavaScript

    config.preferences.javaScriptEnabled = YES;

    //不通过用户交互,是否可以打开窗口

    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;


    self.webView=[[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];

    _webView.navigationDelegate=self;

    _webView.UIDelegate = self;


//

    NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *path = [[documentArray lastObject] stringByAppendingPathComponent:@"Preferences"];

    NSURL *url=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/dist/index.html",path]];

    NSString*urlStr = [urlabsoluteString];

    urlStr = [urlStrstringByReplacingOccurrencesOfString:@"file://" withString:@""];

   [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:urlStr]]];

    //uiwebview和wkwebview加载方式略有不同 wkwebview用loadrequest方法不能加载本地html  但是用以上方法可以 应该是后面的 fileURLWithPath起作用了

    [self.viewaddSubview:self.webView];


附demo地址  https://github.com/fc931127/xaizaizip.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容