SSZipArchiveでパスワード付きzipファイルを扱う
iOSアプリ開発でパスワード付きのzipファイルを扱う機会があったので、
SSZipArchiveというライブラリが便利そうだったので、扱い方のメモになります。
- SSZipArchiveのライブラリをダウンロード
- ダウンロードしたライブラリをプロジェクトに追加
- libz.dylibを追加
- パスワード付きzipファイルの用意
- 実装の解説
- サンプルコード
1. SSZipArchiveのライブラリをダウンロード
GitHub - ZipArchive/ZipArchive: ZipArchive is a simple utility class for zipping and unzipping files on iOS and Mac.
2. ダウンロードしたライブラリ内のSSZipArchiveフォルダごとプロジェクトに追加
3. プロジェクトのTARGETS>Build Phases>Link Binary With Libraries でlibz.dylibを追加
4. パスワード付きzipファイルの用意
ここではテストでphoto1.zipというzipファイルを用意しました。
中身はphoto1.jpgという画像ファイルです。
このzipファイルをプロジェクトに追加しておきます。
photo1.jpg→photo1.zipへのパスワード付きzip圧縮は、Macのターミナルで以下のコマンドで行いました。
$ zip -e -r photo1.zip photo1.jpg
5. 実装
#import "SSZipArchive.h"を記述して実装していきます。
パスワード付きzipを解凍するSSZipArchiveのメソッド
// Unzip + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error delegate:(id<SSZipArchiveDelegate>)delegate;
この他にも、SSZipArchive.hでいくつかメソッドが宣言されていますが、今回はこれを利用しました。
引数の種類はこんな感じです
unzipFileAtPath: プロジェクトに追加したzipファイルのパスの文字列
toDestination: 解凍したzipの中身を展開する場所のパスの文字列
overwrite: 上書きを許可するかどうかのBOOL値
password: zipのパスワードの文字列
error: エラー参照の設定
delegate: デリゲートの設定
デリゲートを設定しておけば、zip解凍の処理が完了した時に以下のメソッドが呼ばれるので、ここでzipの中身のファイルを読み込んで利用する処理を実装します。
- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath
6. サンプルコード
例として、ViewController.m内に実装してみました。
#import "ViewController.h" #import "SSZipArchive.h" @interface ViewController () <SSZipArchiveDelegate> @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // パスワード付きzipを解凍する NSString *zipFilePath = [[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"zip"]; NSString *destinationPath = NSTemporaryDirectory(); NSString *password = @"12345"; NSError *error = nil; [SSZipArchive unzipFileAtPath:zipFilePath toDestination:destinationPath overwrite:YES password:password error:&error delegate:self]; if (error) { // エラーが発生した場合 NSLog(@"error:%@", error); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - SSZipArchiveDelegate - (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath { // 解凍したzipファイルから画像ファイルを読み込んでUIImageViewに設定する NSString *filePath = [NSString stringWithFormat:@"%@/photo1.jpg",unzippedPath]; NSData *photoData = [NSData dataWithContentsOfFile:filePath]; self.imageView.image = [UIImage imageWithData:photoData scale:[[UIScreen mainScreen] scale]]; }
今回のサンプルコード
GitHub - travitu/ZipArchiveSample