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]; }
相關文章
相關標籤/搜索