使用AFNetworking在iOS中下载文件

问题描述:

我希望能够使用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”。

任何想法?

+0

我想你会在这里找到解决方案。 http://*.com/questions/8004808/afnetworking-using-afhttprequestoperation-to-download-file –

+0

该解决方案有几乎一样的我的解决方案(使用AFHTTPRequestOperation) – Demasterpl

下载文件:

NSData* data = [[NSData alloc] initWithContentsOfURL:/*your URL*/]; 

并稍后保存:

NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"]; 
    [data writeToFile:path atomically:YES]; 

或者你读CFNetworkDownload_ZkSW5n.tmp与PDF扩展写:

NSData* data = [[NSData alloc] initWithContentsOfFile: PathYourFile]; 
    //save code above 
+0

这并不能掩盖AFNetowrking(你使用所有Apple API),也不支持暂停,进度条或恢复。 ( – Demasterpl

+0

我编辑我的答案) – user2828120

+0

也许'[操作setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *操作,id响应对象) { NSData * data =(NSData *)responseObject; }' – user2828120

- (void)downloadFile{ 

NSURL *url = [NSURL URLWithString:@"http://198.61.234.81/expris/uploads/attachments/file_1.pdf"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
AFHTTPSessionManager *session = [AFHTTPSessionManager manager]; 
NSProgress *progress; 
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 

    NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]]; 

    //Here is change 
    return [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]]; 

}completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 

    [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL]; 

    dispatch_async(dispatch_get_main_queue(), ^(void){ 

     NSLog(@"File downloaded to: %@", filePath); 


    }); 

}]; 

[downloadTask resume]; 
[progress addObserver:self 
      forKeyPath:@"fractionCompleted" 
       options:NSKeyValueObservingOptionNew 
       context:NULL]; 

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ 
NSProgress *progress = (NSProgress *)object; 
NSLog(@"Progress… %f", progress.fractionCompleted); 
} 
+0

请删除观察者,因为它是由于这个崩溃,并删除这一切后工作正常。 –

+0

已被更新回答。感谢@DhruvNarayanSingh指点。 – Spydy

+0

,你提供了很好的答案。 –