.h文件中写这个方法
typedef void(^CompletionDown)(BOOL isSuccess,NSError *error, NSURL *path);
#pragma mark -----下载文件------
+(void)downLandWithUrl:(NSString*)urlString WithSavePath:(NSString *)saveFileName success:(CompletionDown)block3;
.m文件中直接写这些就可以
创建了下载文件的位置
//下载
+(void)downLandWithUrl:(NSString*)urlString WithSavePath:(NSString *)saveFileName success:(CompletionDown)block3
{
//获取沙盒路径
NSString *sanboxDicPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask, YES)objectAtIndex:0];
//创建文件夹
NSString *directory = [sanboxDicPathstringByAppendingPathComponent:@"pdf"];
NSFileManager *fileManager = [NSFileManagerdefaultManager];
BOOL fileExists = [fileManagerfileExistsAtPath:directory];
NSError *directoryCreateError =nil;
if (!fileExists) {//文件夹不存在,创建
[fileManager createDirectoryAtPath:directorywithIntermediateDirectories:YESattributes:nilerror:&directoryCreateError];
}
if (directoryCreateError) {
block3(NO,directoryCreateError,nil);
return;
}
NSString *savePath = [directorystringByAppendingPathComponent:saveFileName];
// NSOutputStream*outputStream = [NSOutputStream outputStreamToFileAtPath:savePath append:NO];
// 1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];
// 2.设置请求的URL地址
NSURL *url = [NSURLURLWithString:urlString];
// 3.创建请求对象
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
// 4.下载任务
NSURLSessionDownloadTask *task = [managerdownloadTaskWithRequest:request progress:^(NSProgress *_Nonnull downloadProgress) {
// 下载进度
// NSLog(@"当前下载进度为:%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
} destination:^NSURL *_Nonnull(NSURL *_Nonnull targetPath, NSURLResponse *_Nonnull response) {
// 下载地址
NSLog(@"默认下载地址%@",targetPath);
// 设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
NSString *filePath =savePath;
return [NSURLfileURLWithPath:filePath]; //返回的是文件存放在本地沙盒的地址
} completionHandler:^(NSURLResponse *_Nonnull response, NSURL *_Nullable filePath, NSError *_Nullable error) {
// 下载完成调用的方法
NSLog(@"%@---%@", response, filePath);
block3(YES,nil,filePath);
}];
// 5.启动下载任务
[task resume];
}
[NetWokingdownLandWithUrl:url WithSavePath:@"20161001.docx"success:^(BOOL isSuccess,NSError *error, NSURL *path) {
if (isSuccess) {
[MBProgressHUDhideHUD];
[MBProgressHUDshowSuccess:@"下载成功"];
}
}];
项目图片