【问题标题】:Download file in iPhone Device在 iPhone 设备中下载文件
【发布时间】:2015-09-09 09:48:56
【问题描述】:
【问题讨论】:
标签:
ios
objective-c
download
asihttprequest
【解决方案1】:
首先ASIHTTPRequest已经过时,请避免使用。
这是使用AFNetworking 下载任何文件并将其保存到您想要的任何位置的代码(savePath)
#define kDocumentsDirPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
- (void)downloadFile:(NSString *)filePath
{
AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:filePath]];
NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request
progress:nil
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSString *savePath = [kDocumentsDirPath stringByAppendingPathComponent:fileName];
return [NSURL fileURLWithPath:savePath];
}
completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (error)
{
NSLog(@"Download failed for %@: %@", fileName, error.localizedDescription);
[[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Failed to download %@", fileName]
message:error.localizedDescription
delegate:nil
cancelButtonTitle:@"Uh Oh"
otherButtonTitles:nil] show];
}
else {
NSLog(@"File downloaded: %@", fileName);
}
}];
[downloadTask resume];
}