概述: 首先 导入ASI网络请求框架 ASI 需要导入的系统库 : CFNetwork.framework SystemConfiguration.framework MobileCoreServices.framework CoreGraphics.framework libz.dylib
本功能主要使用到 ASIHTTPRequest 和 ASINetworkQueue
.h 文件
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
@interface DownLoadManage : NSObject
@property (nonatomic)double fileSiz; //文件全部大小
@property (nonatomic)long long DidDownLoadLenth; //已经下载的文件大小
@property (nonatomic,strong)ASINetworkQueue *netWorkQueue; //下载队列
+ (DownLoadManage *)DefaultManage;
-(void)createQuue;
- (void)startDownLoadFileByFile:(SongsList *)songlist;
#import "DownLoadManage.h"
#define RequestOutTime 120 //设置超时时间
@implementation DownLoadManage
static DownLoadManage *downLoadManage = nil;
+ (id)DefaultManage{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
downLoadManage = [[DownLoadManage alloc] init];
});
return downLoadManage;
}
//创建异步队列
- (void)createQuue {
if (self.netWorkQueue == nil) {
ASINetworkQueue *que = [[ASINetworkQueue alloc] init];
self.netWorkQueue = que;
[self.netWorkQueue reset];
[self.netWorkQueue setShowAccurateProgress:YES];
[self.netWorkQueue setShouldCancelAllRequestsOnFailure:NO];
[self.netWorkQueue setMaxConcurrentOperationCount:1];
[self.netWorkQueue go];
// 创建存放路径
//初始化Documents路径
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//初始化临时文件路径
NSString *folderPath = [path stringByAppendingPathComponent:@"/DownLoad/temp"];
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//判断temp文件夹是否存在
BOOL fileExists = [fileManager fileExistsAtPath:folderPath];
if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹
[fileManager createDirectoryAtPath:folderPath
withIntermediateDirectories:YES
attributes:nil
error:nil];
}
}
}
//创建请求并将请求加入队列
- (void)startDownLoadFileByFile:(NSString *)fileName {
//初始化保存路径
NSString *savePath = [FileSavePath stringByAppendingPathComponent:[NSString stringWithFormat:@"DownLoad/%@.mp3",fileName]];
//初始下载连接
NSString *strUrl = [NSString stringWithFormat:@"http://bcs.duapp.com/preschoolteaching/song/%@.mp3",songlist.songName];
NSString *URL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:URL];
//设置下载连接
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
//设置ASIHTTPRequest代理
request.delegate = self;
//初始化保存ZIP文件路径
NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"book_%d.zip",[sender tag]]];
//初始化临时文件路径
NSString *tmpDir = NSTemporaryDirectory();
NSString *tempPath = [tmpDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3.temp",songlist.songName]];
//设置文件保存路径
[request setDownloadDestinationPath:savePath];
//设置临时文件路径
[request setTemporaryFileDownloadPath:tempPath];
//设置进度条的代理,
[request setDownloadProgressDelegate:self];
//设置是是否支持断点下载
[request setAllowResumeForFileDownloads:YES];
//设置超时时间
[request setTimeOutSeconds:RequestOutTime];
//设置基本信息 用来标记请求
[request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:songlist.songTag,@"bookID",songlist.songName,@"fileName",nil]];
//添加到ASINetworkQueue队列去下载
[self.netWorkQueue addOperation:request];
}
#pragma mark ASIHTTPRequestDelegate method
//ASIHTTPRequestDelegate,下载之前获取信息的方法,主要获取下载内容的大小,可以显示下载进度多少字节
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
//获取 请求对象的标记
int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];
//文件开始下载
}
//下载中
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes {
//获取 请求对象的标记
//下载中
}
//ASIHTTPRequestDelegate,下载完成时,执行的方法
- (void)requestFinished:(ASIHTTPRequest *)request {
int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];
//下载完成设置文件 防止备份到iCloud和iTunes上
NSString *fileName = [request.userInfo objectForKey:@"fileName"];
NSString *savePath = [FileSavePath stringByAppendingPathComponent:[NSString stringWithFormat:@"DownLoad/%@.mp3",fileName]];
NSURL *url = [NSURL fileURLWithPath:savePath];
[self addSkipBackupAttributeToItemAtURL:url];
if ([self.delegate respondsToSelector:@selector(DownLoadManageaSIdidFinishDownLoadByid:)]) {
[self.delegate DownLoadManageaSIdidFinishDownLoadByid:bookid];
}
}
- (void)requestFailed:(ASIHTTPRequest *)request {
//获取 请求对象的标记
int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];
//文件下载失败
}
//下载完成设置文件 防止备份到iCloud和iTunes上
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
VSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}else {
VSLog(@"防止备份属性设成功");
}
return success;
}