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

来源:互联网 发布:c4d中文版软件 编辑:程序博客网 时间:2024/05/19 03:23

概述: 首先 导入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)longlong DidDownLoadLenth; //已经下载的文件大小

@property (nonatomic,strong)ASINetworkQueue *netWorkQueue; //下载队列

+ (DownLoadManage *)DefaultManage;

-(void)createQuue;

- (void)startDownLoadFileByFile:(SongsList *)songlist;


.m 文件

#import "DownLoadManage.h"

#define RequestOutTime 120 //设置超时时间

@implementation DownLoadManage

staticDownLoadManage *downLoadManage = nil;

+ (id)DefaultManage{

   static dispatch_once_t onceToken;

   dispatch_once(&onceToken, ^{

        downLoadManage = [[DownLoadManagealloc] init];

    });

    returndownLoadManage;

}

//创建异步队列

- (void)createQuue {

    

   if (self.netWorkQueue ==nil) {


        ASINetworkQueue   *que = [[ASINetworkQueuealloc] init];

       self.netWorkQueue = que;

        

        [self.netWorkQueuereset];

        [self.netWorkQueuesetShowAccurateProgress:YES];

        [self.netWorkQueuesetShouldCancelAllRequestsOnFailure:NO];

        [self.netWorkQueuesetMaxConcurrentOperationCount:1];

        [self.netWorkQueuego];

        

        // 创建存放路径

        //初始化Documents路径

        NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];

        //初始化临时文件路径

       NSString *folderPath = [path stringByAppendingPathComponent:@"/DownLoad/temp"];

        //创建文件管理器

       NSFileManager *fileManager = [NSFileManagerdefaultManager];

        //判断temp文件夹是否存在

       BOOL fileExists = [fileManager fileExistsAtPath:folderPath];

        

        if (!fileExists) {//如果不存在说创建,因为下载时,不会自动创建文件夹

            [fileManagercreateDirectoryAtPath:folderPath

                   withIntermediateDirectories:YES

                                   attributes:nil

                                        error:nil];

        }

    }

    

}

//创建请求并将请求加入队列

- (void)startDownLoadFileByFile:(NSString *)fileName {


    //初始化保存路径

    NSString *savePath = [FileSavePath stringByAppendingPathComponent:[NSStringstringWithFormat:@"DownLoad/%@.mp3",fileName]];

    

    //初始下载连接

    NSString *strUrl = [NSStringstringWithFormat:@"http://bcs.duapp.com/preschoolteaching/song/%@.mp3",songlist.songName];

    NSString *URL = [strUrlstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

   NSURL *url = [NSURLURLWithString:URL];

//设置下载连接

ASIHTTPRequest *request = [[ASIHTTPRequestalloc] initWithURL:url];

//设置ASIHTTPRequest代理

request.delegate =self;

    

       //初始化保存ZIP文件路径

NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"book_%d.zip",[sender tag]]];

//初始化临时文件路径

    NSString *tmpDir =NSTemporaryDirectory();

NSString *tempPath = [tmpDirstringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.mp3.temp",songlist.songName]];

    

//设置文件保存路径

[request setDownloadDestinationPath:savePath];

    

//设置临时文件路径

[request setTemporaryFileDownloadPath:tempPath];

    

    //设置进度条的代理,

[request setDownloadProgressDelegate:self];

    

//设置是是否支持断点下载

[request setAllowResumeForFileDownloads:YES];

    

    //设置超时时间

    [request setTimeOutSeconds:RequestOutTime];

    

//设置基本信息 用来标记请求

[requestsetUserInfo:[NSDictionarydictionaryWithObjectsAndKeys:songlist.songTag,@"bookID",songlist.songName,@"fileName",nil]];

    

    

//添加到ASINetworkQueue队列去下载

[self.netWorkQueueaddOperation: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:(longlong)bytes {

    

//获取 请求对象的标记

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

//下载中    

}


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

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

    

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

    

    

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

   NSString *fileName = [request.userInfoobjectForKey:@"fileName"];

    NSString *savePath = [FileSavePath stringByAppendingPathComponent:[NSStringstringWithFormat:@"DownLoad/%@.mp3",fileName]];

   NSURL *url = [NSURLfileURLWithPath:savePath];

    [selfaddSkipBackupAttributeToItemAtURL:url];

    

    

                          

   if ([self.delegaterespondsToSelector:@selector(DownLoadManageaSIdidFinishDownLoadByid:)]) {

        [self.delegateDownLoadManageaSIdidFinishDownLoadByid:bookid];

    }

}

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

    //获取 请求对象的标记

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

   //文件下载失败

}


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

- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL

{

    assert([[NSFileManagerdefaultManager] fileExistsAtPath: [URLpath]]);

    

   NSError *error = nil;

    BOOL success = [URLsetResourceValue: [NSNumbernumberWithBool: YES]

                                 forKey: NSURLIsExcludedFromBackupKeyerror: &error];

   if(!success){

        VSLog(@"Error excluding %@ from backup %@", [URLlastPathComponent], error);

    }else {

        VSLog(@"防止备份属性设成功");

    }

   return success;

}



0 0
原创粉丝点击