iOS 利用 ASI 实现的异步队列下载文件

概述: 首先 导入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;


.m 文件

#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 {

    

//获取 请求对象的标记

    int bookid = [[request. userInfo objectForKey: @"bookID"] intValue];
   

//下载中    

}


//ASIHTTPRequestDelegate,下载完成时,执行的方法

- (void)requestFinished:(ASIHTTPRequest *)request {

    

    int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];

    

    

    //下载完成设置文件 防止备份到iCloudiTunes

    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];

    //文件下载失败

}


//下载完成设置文件 防止备份到iCloudiTunes

- (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;

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值