ios中文件下载(带缓存)

使用asiHttPRequst框架

封装下载类

#import <Foundation/Foundation.h>
#define FILESDOWNLOADCOMPLETE @"FilesDownloadComplete"  // 文件下载完成
@interface AsynchDownloadFile : NSObject
+(AsynchDownloadFile *)ShareTheme;
-(void)DownLoadFileUrl:(NSString *)aFileUrl;
@end
#import "AsynchDownloadFile.h"
#import "ASIHTTPRequest.h"
#import "ASIDownloadCache.h"//设置缓存类



@interface AsynchDownloadFile ()


@end

@implementation AsynchDownloadFile

#pragma mark -单例
+(AsynchDownloadFile *)ShareTheme{
   
    static dispatch_once_t onceToken;
    static AsynchDownloadFile *loadFile=nil;
    dispatch_once(&onceToken, ^{
        loadFile=[[AsynchDownloadFile alloc] init];
    });
    return loadFile;
}

-(void)DownLoadFileUrl:(NSString *)aFileUrl{
    //首先判断请求连接有没有文件
    NSString *cacheFile=[self cacheFileForImage:aFileUrl];
   NSFileManager *fgr=[NSFileManager defaultManager];
    if([fgr fileExistsAtPath:cacheFile]){//文件存在,直接发送消息
        [[NSNotificationCenter defaultCenter] postNotificationName:FILESDOWNLOADCOMPLETE object:cacheFile];
    }
    else{//下载文件 可以清楚缓存
        [self loadImageFromURL:[NSURL URLWithString:aFileUrl] imgInfoDic:nil];
    }


}

#pragma mark-通过请求得到文件全路径
-(NSString *)cacheFileForImage:(NSString *)imgName{
        //指定缓存文件路径
        NSString *cacheFolder=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        cacheFolder=[cacheFolder stringByAppendingPathComponent:@"新闻类附件"];

        NSFileManager *fmgr=[NSFileManager defaultManager];
        if(![fmgr fileExistsAtPath:cacheFolder]){//如果文件夹不存在,创建
            NSError *error=nil;
            [fmgr createDirectoryAtPath:cacheFolder withIntermediateDirectories:YES attributes:nil error:&error];
            if(error){
                NSLog(@"创建缓存文件夹 失败");
                return nil;
            }
        }
        //文件名字以等号分割
        NSArray *paths=[imgName componentsSeparatedByString:@"="];
        if(paths.count==0)return nil;
        return [NSString stringWithFormat:@"%@/%@",cacheFolder,[paths lastObject] ];
}

#pragma mark -下载文件 并且附带设置缓存
-(void)loadImageFromURL:(NSURL*)aUrl imgInfoDic:(NSDictionary*)infoDic{
    __block ASIHTTPRequest *request=nil;
if(aUrl){
    request=[ASIHTTPRequest requestWithURL:aUrl];
    [request setDelegate:self];
    [request setTimeOutSeconds:60];
    //设置下载缓存
    [request setDownloadCache:[ASIDownloadCache sharedCache]];
    //设置缓存存储策略
    [request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
    
    //设置缓存保存数据时间
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];//永久保存
    [request setShouldContinueWhenAppEntersBackground:YES];//设置后台运行。
    [request setDownloadDestinationPath:[self cacheFileForImage:[aUrl absoluteString]]];//设置缓存路径
    
    }
    else{
        return;
    }

    [request setCompletionBlock:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:FILESDOWNLOADCOMPLETE object:[self cacheFileForImage:[aUrl absoluteString]]];
    }];

    [request setFailedBlock:^{
        NSError *error = [request error];
        NSLog(@"error reason: %@", error);
    }];
    [request startAsynchronous];

}



@end
//直接使用
#import "MMViewController.h" #import "AsynchDownloadFile.h" @interface MMViewController () @end @implementation MMViewController -(void)viewDidLoad{ [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(FileDownloadComplete:) name:FILESDOWNLOADCOMPLETE object:nil]; } - (IBAction)click:(id)sender { NSString *url=@"http://。。。。。?classid=0&filename=110908133300893.doc"; [[AsynchDownloadFile ShareTheme] DownLoadFileUrl:url]; } -(void)FileDownloadComplete:(id)sender{ NSLog(@"--com"); } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; }

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值