.h文件
typedef void(^CompletionDown)(BOOL isSuccess, NSError *error, NSString *path);
/*
下载方法,参数:
urlPath:下载地址,
saveFileName:命名存储文件
*/
+(void)downFileWithUrl:(NSString *)urlPath WithSavePath:(NSString *)saveFileName onCompletionDownLoad:(CompletionDown)block;
.m实现文件
+(void)downFileWithUrl:(NSString *)urlPath WithSavePath:(NSString *)saveFileName onCompletionDownLoad:(CompletionDown)block{
//获取沙盒路径
NSString *sanboxDicPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//创建文件夹
NSString *directory = [sanboxDicPath stringByAppendingPathComponent:@"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [fileManager fileExistsAtPath:directory];
NSError *directoryCreateError = nil;
if (!fileExists) {//文件夹不存在,创建
[fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&directoryCreateError];
}
if (directoryCreateError) {
block(NO,directoryCreateError,nil);
return;
}
NSString *savePath = [directory stringByAppendingPathComponent:saveFileName];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = 70;
AFHTTPRequestOperation *op = [manager GET:urlPath
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"successful download to %@", savePath);
block(YES,nil,savePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
block(NO,error,nil);
}];
[op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"is download:%f", (float)totalBytesRead / totalBytesExpectedToRead);
}];
op.outputStream = [NSOutputStream outputStreamToFileAtPath:savePath append:NO];
[op start];
}