2016-09-12 3 views
2

Я использую SSZipArchive. После загрузки файла я хочу разархивировать архив и показать изображение. Но код не работает. Как это исправить?Как распаковать файл?

загрузить файл

-(IBAction) downloadButton:(id)sender 
    { 
     if (_HighScore == 2) { 

      _url1 =[NSURL URLWithString:@"link2.zip"]; 

      _downloadTask1 = [_session downloadTaskWithURL:_url1]; 

      [_downloadTask1 resume]; 
    } 

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 
{ 

    if (downloadTask == _downloadTask1) { 

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
     NSURL *documentsFolder = [paths objectAtIndex:0]; 

     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     NSURL *newLocation = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@/2.zip", documentsFolder]]; 

     NSError *error; 
     [fileManager copyItemAtURL:location toURL:newLocation error:&error]; 
NSLog(@"file%@", newLocation.absoluteString); 
} 

разархивировать файл

_documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    _zipPath1 = [_documentsDirectory1 stringByAppendingPathComponent:@"2.zip"]; 
    _destinationPath1 = [_documentsDirectory1 stringByAppendingPathComponent:@"file://%@/2.zip"]; 
    _fileExists1 = [[NSFileManager defaultManager] fileExistsAtPath:_zipPath1 isDirectory:false]; 
    if([SSZipArchive unzipFileAtPath:_zipPath1 toDestination:_destinationPath1] != NO) { 
     NSLog(@"Dilip Success"); 
    }else{ 
     NSLog(@"Dilip Error"); 
    } 

UPD

-(IBAction) downloadButton:(id)sender 
{ 
    if (_HighScore == 2) { 

     _url1 =[NSURL URLWithString:@"link2.zip"]; 

     _downloadTask1 = [_session downloadTaskWithURL:_url1]; 

     [_downloadTask1 resume]; 
} 
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 
{ 

    if (downloadTask == _downloadTask1) { 
     _documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
     _zipPath1 = [_documentsDirectory1 stringByAppendingPathComponent:@"2.zip"]; 
    } 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

    if (downloadTask == _downloadTask1) { NSData *urlData1 = [NSData dataWithContentsOfURL:_url1]; [urlData1 writeToFile:_zipPath1 atomically:YES];} 

}); 
} 
+0

между Я заметил, что '[_documentsDirectory1 stringByAppendingPathComponent: @ "/ PDFFolder"]' вы добавляете '/' на самом деле, метод 'stringByAppendingPathComponent' добавляет'/'U не нужно указывать его просто изменить это для '_filePath1 = [_documentsDirectory1 stringByAppendingPathComponent: @" PDFFolder "];' просто использовать 'PDFFolder', заменить его для всех –

+0

не работает ... Я обновляю вопрос. пожалуйста, проверьте. – User

+0

проверили пути и файл zip для загрузки, указанный в указанной папке ..? а также способ загрузки изображения, чтобы изображение отображалось на пути, пока вы загружаете изображение 'UIImage * image1 = [UIImage imageWithContentsOfFile: workSpacePath1];' –

ответ

1

Проблемы заключается в сохранении архива в DocumentDirectory, _filePath1 это содержит папку для разархивируешь, вместо того, что вам нужно использовать filePath которые содержат имя файла zip и путь, поэтому используйте это.

[urlData1 writeToFile:filePath atomically:YES]; 

Также тесто, если вы используете writeToFile:options:error: метод, так что вы можете знать, что успешно писать Data или нет.

NSError *error = nil; 
[self.responseData writeToFile:zipPath options:0 error:&error]; 

Edit: Вы, вероятно, возиться с чем-то, так что изменить код загрузки на сохранение и распаковке, как это.

-(IBAction) downloadButton:(id)sender 
{ 
    if (_HighScore == 2) { 
     _url1 =[NSURL URLWithString:@"link2.zip"]; 
     _downloadTask1 = [session dataTaskWithURL:[NSURL URLWithString:@""] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

      //Saved in NSDocumentDirectory 
      NSError *error = nil; 
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *path = [paths objectAtIndex:0]; 
      NSString *zipPath = [path stringByAppendingPathComponent:@"2.zip"]; 
      [self.responseData writeToFile:zipPath options:0 error:&error]; 

      //UNZip 
      NSString *zipPath1 = [path stringByAppendingPathComponent:@"2.zip"]; 
      NSString *destinationPath = [NSString stringWithFormat:@"%@",path]; 
      [SSZipArchive unzipFileAtPath:zipPath1 toDestination:destinationPath]; 
      //Now access the content of zip 
     }]; 
     [_downloadTask1 resume]; 
    } 
} 
+0

Я обновляю вопрос. пожалуйста, проверьте. в отладке я получаю 'NSLog (@« Dilip Success »);' но изображение не появляется. Зачем? – User

+0

Я обновляю свой вопрос – User

+0

Жаль, что я проверил ваш предыдущий комментарий, вы уверены, что добиваетесь успеха. то в чем проблема? –

0

попробовать, как это, его работа для меня

[SSZipArchive unzipFileAtPath:filePath toDestination:outputPath delegate:self]; 

после завершения разархивировать следующий метод будет вызывать

#pragma mark - Unzipp Delegate 

- (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo: (unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath { 
     //write code here after unarchive zip file 
    } 
+0

не работает ... обновляю вопрос. пожалуйста, проверьте. – User

+0

, пожалуйста, установите флажок после этой строки в вашем коде _filePath1 = [_documentsDirectory1 stringByAppendingPathComponent: @ "PDFFolder"]; а также _filePath2 = [_documentsDirectory2 stringByAppendingPathComponent: @ "PDFFolder"] –

+0

Я обновляю свой вопрос – User

Смежные вопросы