引用libz.dylib和第三方類庫:《ZipHelper》
- (void)viewDidLoad
{
[super viewDidLoad];
//註冊消息
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(callBack) name: @"back" object: nil];
//開新的線程
NSThread *thread=[[NSThread alloc] initWithTarget:self selector:@selector(threadUpdatePre) object:nil];
[thread start];
[thread release];
}
//取沙盒目錄
-(NSString *) getAppStartupPath
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
}
//調用線程事件
-(void)threadUpdatePre
{
//如果主線程中有自動回收池,線程如果要用自動回收池需另開線程池
NSAutoreleasePool *pool=[[NSAutoreleasePoolalloc] init];
//指定下載地址
NSString *urlString=[[[NSStringalloc]initWithFormat:@"http://...../test.zip"]autorelease];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:nil];
NSString *filePath=[[[NSString alloc]initWithFormat:@"%@", [selfgetAppStartupPath]] autorelease];
[datawriteToFile:[filePath stringByAppendingString:@"/test.zip"]atomically:YES];
//向消息中心發送完成消息
[[NSNotificationCenterdefaultCenter] postNotificationName:@"back"object:self];
[pool drain];
}
//接收消息中心消息,回調相應事件
- (void)callBack{
[selfZipToFile];
}
//解壓縮
-(void)ZipToFile{
NSString *filePath=[[NSString alloc]initWithFormat:@"%@", [selfgetAppStartupPath]];
ZipArchive *zp=[[ZipArchivealloc]init];
BOOL isUpdateSucess=YES;
if ([zp UnzipOpenFile:[filePath stringByAppendingString:@"/test.zip"] Password:@"123456"]) {//帶密碼解壓
isUpdateSucess = isUpdateSucess && [zpUnzipFileTo:filePathoverWrite:YES];
[zp UnzipCloseFile];
}elseif([zpUnzipOpenFile:[filePathstringByAppendingString:@"/test.zip"]]){//不帶密碼解壓
isUpdateSucess = isUpdateSucess && [zpUnzipFileTo:filePathoverWrite:YES];
[zp UnzipCloseFile];
}
else{
isUpdateSucess=NO;
}
[zp release];
[filePath release];
}