LoginSignup
101
105

More than 5 years have passed since last update.

iOSでZIPファイルの圧縮/解凍を簡単に実装する方法

Last updated at Posted at 2013-12-08

概要

iOSで手っ取り早くZIPファイルの圧縮/解凍する方法を調べてみました。

zlibを使ってC言語で処理を書くなんてこともできるようですが、
Objective-c 一辺倒の私にはこの方法は却下です。

ZipArchiveというライブラリもありますが、こちらはソースコードが古くARCにも対応していません。
で最終的に行き着いたのがSSZipArchiveというライブラリです。
これはZipArchiveをベースに作られたものでARCにも対応しています。

使い方もとてもシンプルだったのでSSZipArchiveが現時点(2013/12/8)では一番よいかと思います。

使い方

まずgithubからソースを取得しましょう。

ソースコード内のSSZipArchiveディレクトリとその配下にあるminizipディレクトリをプロジェクトに追加します。

libz.dylibをターゲットに追加します。

SSZipArchive.hヘッダーをインポートすることも忘れないように。

解凍するとき

// 解凍
NSString *zipFilePath = @"解凍するZIPファイルのパス";
NSString *destinationPath = @"解凍したファイルを展開するディレクトリのス";
BOOL isSuccess = [SSZipArchive unzipFileAtPath:zipFilePath Destination:destinationPath delegate:self];
if (isSuccess) {
    // 処理が成功した場合
} else {
    // 処理が失敗した場合
}

パスワードを指定する場合

// 解凍
NSString *zipFilePath = @"解凍するZIPファイルのパス";
NSString *destinationPath = @"解凍したファイルを展開するディレクトリのス";
NSString *password = @"パスワード";
NSError *error = nil;
[SSZipArchive unzipFileAtPath:zipFilePath toDestination:destinationPath
                    overwrite:YES password:password error:&error delegate:self];
if (error) {
    // エラーが発生した場合
    NSLog(@"error: %@", error);
}

解凍が完了した場合に処理を実行した場合はデリゲートを設定した上で、下記メソッドを実装する

- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath {
    NSLog(@"解凍完了");
}

圧縮する時

// 圧縮
NSString *zippedFilePath = @"圧縮したZIPファイルの保存先パス";
NSArray *inputFilePaths = @[[[NSBundle mainBundle]
                             pathForResource:@"sampleImage" ofType:@"jpg"],
                            [[NSBundle mainBundle]
                             pathForResource:@"sampleText" ofType:@"txt"]];
BOOL isSuccess = [SSZipArchive createZipFileAtPath:zippedFilePath hFilesAtPaths:inputFilePaths];
if (isSuccess) {
    // 処理が成功した場合
} else {
    // 処理が失敗した場合
}

という事でとても簡単に実装できます。
デリゲートでは無くブロック構文に対応させてもよさそうです。

お試しあれ!

101
105
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
101
105