您的位置:首页 > 其它

使用AFNetworking下载文件

2015-10-10 08:56 337 查看
.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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息