美文网首页
ios zip rar 解压缩

ios zip rar 解压缩

作者: 贝勒老爷 | 来源:发表于2019-01-10 10:21 被阅读126次

    废话不多说直接上代码

    //
    //  UNZipRARService.h
    //  ZHEJIANG
    //
    //  Created by pipixia on 2019/1/3.
    //  Copyright © 2018年 pipixia. All rights reserved.
    
    #import <Foundation/Foundation.h>
    #import <SSZipArchive/SSZipArchive.h>
    #import <UnrarKit/UnrarKit.h>
    #define UNIQUE_KEY( x ) NSString * const x = @#x
    
    enum{
        SARFileTypeZIP,
        SARFileTypeRAR
    };
    
    static UNIQUE_KEY( rar );
    static UNIQUE_KEY( zip );
    
    typedef void(^Completion)(NSArray *filePaths);
    typedef void(^DownLoadFilePath)(NSString *filePath);
    typedef void(^Failure)(void);
    
    @interface UNZipRARService : NSObject <SSZipArchiveDelegate>{
        SSZipArchive *_zipArchive;
        NSString *_fileType;
    }
    
    @property (nonatomic, strong) NSString *filePath;
    @property (nonatomic, strong) NSString *password;
    @property (nonatomic, strong) NSString *destinationPath;
    @property (nonatomic, copy) Completion completionBlock;
    @property (nonatomic, copy) DownLoadFilePath downLoadFilePathBlock;
    @property (nonatomic, copy) Failure failureBlock;
    
    - (id)initWithPath:(NSString *)path;
    - (void)decompress;
    
    @end
    
    
    //
    //  UNZipRARService.m
    //  ZHEJIANG
    //
    //  Created by pipixia on 2019/1/3.
    //  Copyright © 2018年 pipixia. All rights reserved.
    
    #import "UNZipRARService.h"
    
    #define ZWYZIP             @"ZWYZIP"
    #define ZWYRAR             @"ZWYRAR"
    
    
    @implementation UNZipRARService
    
    @synthesize completionBlock;
    @synthesize downLoadFilePathBlock;
    @synthesize failureBlock;
    
    
    #pragma mark - Init Methods
    - (id)initWithPath:(NSString *)path {
        if ((self = [super init])) {
            _filePath = [path copy];
            _fileType = [[NSString alloc]init];
        }
    
        if (_filePath != nil) {
            _destinationPath = [self getDestinationPath];
        }
        return self;
    }
    
    - (id)initWithPath:(NSString *)path andPassword:(NSString*)password{
        if ((self = [super init])) {
            _filePath = [path copy];
            _password = [password copy];
            _fileType = [[NSString alloc]init];
        }
        
        if (_filePath != nil) {
            _destinationPath = [self getDestinationPath];
        }
        return self;
    }
    
    #pragma mark - Helper Methods
    - (NSString *)getDestinationPath{
        NSArray *derivedPathArr = [_filePath componentsSeparatedByString:@"/"];
        NSString *lastObject = [derivedPathArr lastObject];
        _fileType = [[lastObject componentsSeparatedByString:@"."] lastObject];
        return [_filePath stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"/%@",lastObject] withString:@""];
    }
    
    
    #pragma mark - Decompressing Methods
    - (void)decompress{
        //    NSLog(@"_fileType : %@",_fileType);
        if ( [_fileType compare:rar options:NSCaseInsensitiveSearch] == NSOrderedSame ) {
            [self rarDecompress];
        }
        else if ( [_fileType compare:zip options:NSCaseInsensitiveSearch] == NSOrderedSame ) {
            [self zipDecompress];
        }
    
    }
    
    - (void)rarDecompress {
        NSString *tmpDirname = ZWYRAR;
        _destinationPath = [_destinationPath stringByAppendingPathComponent:tmpDirname];
    //    _filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"rar"];
        NSLog(@"filePath : %@",_filePath);
        NSLog(@"destinationPath : %@",_destinationPath);
    
        NSError *archiveError = nil;
        URKArchive *archive = [[URKArchive alloc] initWithPath:_filePath error:&archiveError];
        
        if (!archive) {
            NSLog(@"Failed!");
            return;
        }
        
        NSError *error = nil;
        NSArray *filenames = [archive listFilenames:&error];
        
        if (archive.isPasswordProtected) {
            archive.password = self.password;
        }
        
        if (error) {
            NSLog(@"Error reading archive: %@", error);
            return;
        }
        
    //    for (NSString *filename in filenames) {
    //        NSLog(@"File: %@", filename);
    //    }
        
        // Extract a file into memory just to validate if it works/extracts
        [archive extractDataFromFile:filenames[0] progress:nil error:&error];
        
        if (error) {
            if (error.code == ERAR_MISSING_PASSWORD) {
                NSLog(@"Password protected archive! Please provide a password for the archived file.");
            }
            if (failureBlock != nil) {
                failureBlock();
            }
        }
        else {
            NSMutableArray *filePathsArray = [NSMutableArray array];
            for (NSString *filePath in filenames){
                [filePathsArray addObject:[_destinationPath stringByAppendingPathComponent:filePath]];
            }
            [self moveFilesToDestinationPathFromCompletePaths:filePathsArray withFilePaths:filenames withArchive:archive];
            if (completionBlock != nil) {
                completionBlock(filePathsArray);
            }
        }
        
    }
    
    - (void)zipDecompress{
        NSString *tmpDirname = ZWYZIP;
        _destinationPath = [_destinationPath stringByAppendingPathComponent:tmpDirname];
        BOOL unzipped = [SSZipArchive unzipFileAtPath:_filePath toDestination:_destinationPath delegate:self];
    //    NSLog(@"unzipped : %d",unzipped);
        NSError *error;
        if (self.password != nil && self.password.length > 0) {
            unzipped = [SSZipArchive unzipFileAtPath:_filePath toDestination:_destinationPath overwrite:YES password:self.password error:&error delegate:self];
            NSLog(@"error: %@", error);
        }
        
        if ( !unzipped ) {
            failureBlock();
        }
    }
    
    #pragma mark - SSZipArchive Delegates
    - (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath WithFilePaths:(NSMutableArray *)filePaths{
        //    NSLog(@"path : %@",path);
        //    NSLog(@"unzippedPath : %@",unzippedPath);
        completionBlock(filePaths);
    }
    
    - (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath
    {
        downLoadFilePathBlock(unzippedPath);
    }
    
    - (void)zipArchiveDidUnzipArchiveFile:(NSString *)zipFile entryPath:(NSString *)entryPath destPath:(NSString *)destPath
    {
        
    }
    
    #pragma mark - Utility Methods
    - (NSString *) applicationDocumentsDirectory
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        return basePath;
    }
    
    
    #pragma mark - Not using these methods now
    //Writing this for Unrar4iOS, since it just unrar's(decompresses) the files into the compressed(rar) file's folder path
    - (void)moveFilesToDestinationPathFromCompletePaths:(NSArray *)completeFilePathsArray withFilePaths:(NSArray *)filePathsArray withArchive:(URKArchive*)archive{
        
        NSError *error;
        [archive extractFilesTo:_destinationPath overwrite:NO progress:^(URKFileInfo *currentFile, CGFloat percentArchiveDecompressed) {
    //        NSLog(@"Extracting %@: %f%% complete", currentFile.filename, percentArchiveDecompressed);
        } error:&error];
        NSLog(@"Error: %@", error);
    }
    
    @end
    

    用的时候这么用

    zip解压缩
    
    - (void)unZip{
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Zip_Example" ofType:@"zip"];
        
        NSString *destPath = [self applicationDocumentsDirectory];
        [self unArchive:filePath andPassword:nil destinationPath:destPath];
        
    }
    
    - (NSString *)applicationDocumentsDirectory
    {
    //    NSString *cachesPath = [CreateFileService getFilePathByName:savePath];
    //    NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
    
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        return basePath;
    }
    
    
    - (void)unArchive: (NSString *)filePath andPassword:(NSString*)password destinationPath:(NSString *)destPath{
        NSAssert(filePath, @"can't find filePath");
        UNZipRARService *unarchive = [[UNZipRARService alloc]initWithPath:filePath];
        if (password != nil && password.length > 0) {
            unarchive.password = password;
        }
        
        if (destPath != nil)
            
            unarchive.destinationPath = destPath;//(Optional). If it is not given, then the file is unarchived in the same location of its archive/file.
        
        unarchive.downLoadFilePathBlock = ^(NSString *filePath){
            //zip取
            NSLog(@"%@",filePath);
            patchStr = filePath;
        };
        unarchive.completionBlock = ^(NSArray *filePaths){
            //rar取
            NSLog(@"For Archive : %@",filePath);
            for (NSString *filename in filePaths) {
                NSLog(@"Extracted Filepath: %@", filename);
            }
            //        NSLog(@"filePaths.count: %d", filePaths.count);
        };
        unarchive.failureBlock = ^(){
            NSLog(@"Cannot be unarchived");
        };
        [unarchive decompress];
    }
    
    rar
    
    - (void)unRar{
        //rarwenjian
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"rarwenjian" ofType:@"rar"];
        
        NSString *destPath = [self applicationDocumentsDirectory];
        [self unArchive:filePath andPassword:nil destinationPath:destPath];
    }
    
    - (NSString *)applicationDocumentsDirectory
    {
    //    NSString *cachesPath = [CreateFileService getFilePathByName:savePath];
    //    NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
    
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        return basePath;
    }
    
    - (void)unArchive: (NSString *)filePath andPassword:(NSString*)password destinationPath:(NSString *)destPath{
        NSAssert(filePath, @"can't find filePath");
        UNZipRARService *unarchive = [[UNZipRARService alloc]initWithPath:filePath];
        if (password != nil && password.length > 0) {
            unarchive.password = password;
        }
        
        if (destPath != nil)
            
            unarchive.destinationPath = destPath;//(Optional). If it is not given, then the file is unarchived in the same location of its archive/file.
        
        unarchive.downLoadFilePathBlock = ^(NSString *filePath){
            //zip取
            NSLog(@"%@",filePath);
            patchStr = filePath;
        };
        unarchive.completionBlock = ^(NSArray *filePaths){
            //rar取
            NSLog(@"For Archive : %@",filePath);
            for (NSString *filename in filePaths) {
                NSLog(@"Extracted Filepath: %@", filename);
            }
            //        NSLog(@"filePaths.count: %d", filePaths.count);
        };
        unarchive.failureBlock = ^(){
            NSLog(@"Cannot be unarchived");
        };
        [unarchive decompress];
    }
    
    

    相关文章

      网友评论

          本文标题:ios zip rar 解压缩

          本文链接:https://www.haomeiwen.com/subject/tyuorqtx.html