AFN下載可以分為三個(gè)部分,初始化sessionManage對(duì)象,設(shè)置下載地址和儲(chǔ)存路徑,下載進(jìn)度
初始化對(duì)象
/* 創(chuàng)建網(wǎng)絡(luò)下載對(duì)象 */
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
設(shè)置下載地址和儲(chǔ)存路徑
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文件是自己創(chuàng)建的,創(chuàng)建方法 iOS中在沙盒中創(chuàng)建文件夾
下載進(jìn)度
/* 開(kāi)始請(qǐng)求下載 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下載進(jìn)度:%.0f%", downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
dispatch_async(dispatch_get_main_queue(), ^{
//如果需要進(jìn)行UI操作,需要獲取主線程進(jìn)行操作
});
/* 設(shè)定下載到的位置 */
return [NSURL fileURLWithPath:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"下載完成");
[self extract];
}];
[downloadTask resume];
至此,一個(gè)基于AFNetworking的文件下載就OK了。