简体   繁体   English

在ios中压缩doc文件并将其保存到文档目录

[英]Zip the doc file in ios and save in to document directory

I would like to save a doc file into a zip file in the document directory and when the user chooses they can attach it in an email. 我想将文档文件保存到文档目录中的zip文件中,并且当用户选择时,可以将其附加到电子邮件中。 I have created the zip file but when I want to open it again it creates a zipfile, zip.cpgz instead of testing.zip . 我已经创建了一个zip文件,但是当我想再次打开它时,它会创建一个zip.cpgz而不是testing.zip

Here is my code for creating the zip file 这是我创建zip文件的代码

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];

int index =0;
for (NSString *item in filePathsArray){
    if ([[item pathExtension] isEqualToString:@"doc"])
    {
       NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:index]];
        //NSString *FileName=[stringPath1 stringByAppendingPathComponent:@"Console.doc"];

        NSString *stringPath=[documentsDirectory stringByAppendingPathComponent:[@"testing" stringByAppendingFormat:@".zip"]];

        ZipFile *zipFile = [[ZipFile alloc]initWithFileName:stringPath mode:ZipFileModeCreate];


        ZipWriteStream *stream= [zipFile writeFileInZipWithName:@"doc" compressionLevel:ZipCompressionLevelBest];
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        [stream writeData:data];
        [stream finishedWriting];

    }
}

You must use ssziparchive 您必须使用ssziparchive

An Utility class for zipping and unzipping files for iOS 一个实用程序类,用于为iOS压缩和解压缩文件

Example provided:- 提供的示例:

// Unzipping
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];


    // Zipping
    NSString *zippedPath = @"path_where_you_want_the_file_created";
    NSArray *inputPaths = [NSArray arrayWithObjects:
                           [[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"jpg"],
                           [[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"]
                           nil];
    [SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM