在我的iOS應用程序中,我使用AFNetworking
庫來管理所需的HTTP操作。AFNetworking當請求成功時下載並保存數據
我創建了一個方法來下載文件:
+ (void)downloadFile:(File *)file progress:(void (^)(NSUInteger receivedBytes, long long totalReceivedBytes, long long totalExpectedBytes))progress success:(void (^)())success failure:(void (^)(NSError *error))failure
{
NSURLRequest *request = [NSURLRequest requestWithURL:file.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[FCFileManager pathForTemporaryDirectoryWithPath:file.key.lastPathComponent] append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
progress(bytesRead, totalBytesExpectedToRead, totalBytesExpectedToRead);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
success();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
failure(error);
}];
[operation start];
}
雖然沒有采用這種方法的一個問題。如果正在取消下載(強制退出),則仍然可以在應用程序目錄中找到該文件。如何創建文件下載,僅在下載成功完成時纔將文件保存到文檔目錄?
也許在completionBlock中你可以捕捉到operation.error。如果爲零,則下載完成。 – Quetool