我希望能夠使用AFNetworking下載文件,該文件支持:ProgressBar,暫停和恢復下載。使用AFNetworking在iOS中下載文件
在接近這個我自己,我能夠想出這個代碼,但它不支持暫停或恢復:
-(void)downloadFile:(NSString *)UrlAddress indexPathofTable:(NSIndexPath *)indexPath
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:UrlAddress]];
NSString *pdfName = [self pdfNameFromURL:UrlAddress];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pdfName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"Successfully downloaded file to %@", path);
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Error: %@", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
//do something in this line with the calculation to cell
float progress = (float)totalBytesRead/totalBytesExpectedToRead;
[[NSNotificationCenter defaultCenter] postNotificationName:[NSString stringWithFormat:@"progress-%ld-%ld", (long)indexPath.section, (long)indexPath.row] object:@(progress)]; //Working reporting progress in cellForRowAtIndexPath.
//NSLog(@"Download = %f", progress);
}];
[operation start];
}
事情是,我不知道如何管理暫停&恢復。
看着他們的文檔:(https://github.com/AFNetworking/AFNetworking),他們提供了不同的方式來下載文件:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://www.irs.gov/pub/irs-pdf/fw4.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
我期望「fw4.pdf」在我的iOS」的文件夾正確命名。然而,這是記錄的結果:
文件下載到:文件:///Users/myName/Library/Application%20Support/iPhone%20Simulator/7.0/Applications/F4C3BC41-70B4-473A-B1F6-D4BC2A6D0A4F/Documents /CFNetworkDownload_ZkSW5n.tmp
上面的文件被下載,但帶有怪異的臨時名稱。
我在我自己的代碼中實現我正在使用「AFHTTPRequestOperation」對象,而他們正在使用「AFURLSessionManager」。
任何想法?
我想你會在這裏找到解決方案。 http://stackoverflow.com/questions/8004808/afnetworking-using-afhttprequestoperation-to-download-file –
該解決方案有幾乎一樣的我的解決方案(使用AFHTTPRequestOperation) – Demasterpl