2012-08-29 6 views
6

내 iPad 앱으로 큰 .zip 파일 (최대 800MB)을 다운로드해야합니다. 취소되거나 앱이 백그라운드에있는 경우 다운로드를 다시 시작하고 싶습니다.AFNetworking + 큰 파일 다운로드 일시 중지/다시 시작

operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){ 

// unzip the .zip 


}failure:^(AFHTTPRequestOperation *operation, NSError *error){ 

//Handle the error 

}]; 


[operation setDownloadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten,long long totalBytesExpectedToWrite) { 

//update the progressView 

}]; 

[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{ 

// What I have to do here? 

}]; 

[operation start]; 
[operation waitUntilFinished]; 


-(void)applicationWillResignActive:(UIApplication *)application{ 

// What I have to do here? 

} 

도움 주셔서 감사합니다.

답변

23

AFDownloadRequestOperation을 사용하여이 작업을 수행 할 수 있습니다.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"....zip"]]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"....zip"]; 
    AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES]; 
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     NSLog(@"Successfully downloaded file to %@", path); 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error: %@", error); 
    }]; 
    [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) { 
     NSLog(@"Operation%i: bytesRead: %d", 1, bytesRead); 
     NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead); 
     NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected); 
     NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile); 
     NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile); 
    }]; 
    [operations addObject:operation]; 

앱을 다시 시작하고 동일한 URL을 가진 요청을 생성하면 다운로드가 다시 시작됩니다. "shouldResume : YES"가 작동합니다.

+1

ARC 이외의 대안이 있습니까? – Tudorizer

+0

URL 리디렉션과 함께 작동하는지 알고 계십니까? 나는 다운로드 한 실제 파일로 리디렉션하는 url을 미리 할당했습니다. 이 URL을 사용하여 다운로드가 재개되지 않는 것 같습니다. –

+0

매번 동일한 targetPath를 지정했는지 확인하십시오. 또한 디렉토리 일 수 없습니다. 디렉토리를 지정하면 URL을 사용하여 파일의 이름을 지정합니다. – mrgrieves