AFN下载可以分为三个部分,初始化sessionManage对象,设置下载地址和储存路径,下载进度
初始化对象
/* 创建网络下载对象 */
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
设置下载地址和储存路径
NSString * urlStr = [NSString stringWithFormat:@"http://files.lqfast.com:8030/xxxxx"];
/* 下载地址 */
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/* 下载路径 */
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Announcement"];
NSString *filePath = [path stringByAppendingPathComponent:url.lastPathComponent];
其中@"Documents/Announcement"
是指定下载到沙盒下Announcement
文件夹中,Announcement
文件是自己创建的,创建方法 iOS中在沙盒中创建文件夹
下载进度
/* 开始请求下载 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下载进度:%.0f%", downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
dispatch_async(dispatch_get_main_queue(), ^{
//如果需要进行UI操作,需要获取主线程进行操作
});
/* 设定下载到的位置 */
return [NSURL fileURLWithPath:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"下载完成");
[self extract];
}];
[downloadTask resume];
至此,一个基于AFNetworking
的文件下载就OK了。
网友评论