iOS 使用AFNetWorking下载文件

使用AFNetWorking下载文件时,需要包含AFNetWorking框架(使用的是2.3.0版本)

当只需单个文件下载时,可以使用单例模式
.h 文件

#import 

@interface DownLoadOrUpLoadFileManager : NSObject

@property (nonatomic, strong) AFHTTPRequestSerializer *serializer;
@property (nonatomic, strong) AFHTTPRequestOperation *downLoadOperation;

+ (instancetype)getInstance;

#pragma mark -下载文件
/**
 *  根据url判断是否已经保存到本地了
 *
 *  @param created 文件的创建时间  通过和fileName拼接成完整的文件路径
 *
 *  @param fileName 文件的名字
 *
 *  @return YES:本地已经存在,NO:本地不存在
 */
- (BOOL)isSavedFileToLocalWithCreated:(UInt32)created fileName:(NSString *)fileName;

/**
 *  根据文件的创建时间 设置保存到本地的路径
 *
 *  @param created  创建时间
 *  @param fileName 名字
 *
 *  @return <#return value description#>
 */
-(NSString *)setPathOfDocumentsByFileCreated:(UInt32)created fileName:(NSString *)fileName;

/**
 *  根据文件类型、名字、创建时间获得本地文件的路径,当文件不存在时,返回nil
 *
 *  @param fileType 文件类型
 *  @param fileName 文件名字
 *  @param created  文件在服务器创建的时间
 *
 *  @return
 */
- (NSURL *)getLocalFilePathWithFileType:(HomeWorkFileType)fileType fileName:(NSString *)fileName fileCreated:(UInt32)created;

/**
 *  @brief 下载文件
 *
 *  @param paramDic   额外的参数
 *  @param requestURL 下载的url
 *  @param fileType   文件类型
 *  @param fileName   文件名字
 *  @param created    文件服务器创建时间
 *  @param success
 *  @param failure
 *  @param progress
 */
- (void)downloadFileWithOption:(NSDictionary *)paramDic
                   withFileUrl:(NSString*)requestURL
                      fileType:(HomeWorkFileType)fileType
                      fileName:(NSString *)fileName
                   fileCreated:(UInt32)created
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress, long long downloadLength, long long totleLength))progress;

/**
 *  取消下载,并删除本地已经下载了的部分
 *
 *  @param created  文件在服务器创建的时间
 *  @param fileName 文件的名字
 */
- (void)cancleDownLoadFileWithServiceCreated:(UInt32)created fileName:(NSString *)fileName;

/**
 *  正在下载中
 *
 *  @return
 */
- (BOOL)isDownLoadExecuting;

/**
 *  下载暂停
 */
- (void)downLoadPause;

/**
 *  下载继续
 */
- (void)downLoadResume;

.m 文件


@implementation DownLoadOrUpLoadFileManager

+ (instancetype)getInstance
{
    static DownLoadOrUpLoadFileManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DownLoadOrUpLoadFileManager alloc]init];
        manager.serializer = [AFHTTPRequestSerializer serializer];
    });
    return manager;
}

/**
 *  根据url判断是否已经保存到本地了
 *
 *  @param url 文件的url
 *
 *  @return YES:本地已经存在,NO:本地不存在
 */
- (BOOL)isSavedFileToLocalWithCreated:(UInt32)created fileName:(NSString *)fileName
{
    // 判断是否已经离线下载了
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%d/%@", LOCAL_SAVE_PATH, created, fileName]];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    if ([filemanager fileExistsAtPath:path]) {
        return YES;
    }
    return NO;
}

/**
 *  根据文件的创建时间 设置保存到本地的路径
 *
 *  @param created  创建时间
 *  @param fileName 名字
 *
 *  @return <#return value description#>
 */
-(NSString *)setPathOfDocumentsByFileCreated:(UInt32)created fileName:(NSString *)fileName
{
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%d", LOCAL_SAVE_PATH, created]];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    if (![filemanager fileExistsAtPath:path]) {
        [filemanager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

/**
 *  根据文件类型、名字、创建时间获得本地文件的路径,当文件不存在时,返回nil
 *
 *  @param fileType 文件类型
 *  @param fileName 文件名字
 *  @param created  文件在服务器创建的时间
 *
 *  @return
 */
- (NSURL *)getLocalFilePathWithFileType:(HomeWorkFileType)fileType fileName:(NSString *)fileName fileCreated:(UInt32)created
{
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%d", LOCAL_SAVE_PATH, created]];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    NSArray *fileList = [filemanager subpathsOfDirectoryAtPath:path error:nil];
    
    if ([fileList containsObject:fileName]) {
        NSString *fileUrltemp = [NSString stringWithFormat:@"%@/%@", path, fileName];
        NSURL *url = [NSURL fileURLWithPath:fileUrltemp];
        return url;
    }
    return nil;
}

/**
 *  @brief 下载文件
 *
 *  @param paramDic   额外的参数
 *  @param requestURL 下载的url
 *  @param fileType   文件类型
 *  @param fileName   文件名字
 *  @param created    文件服务器创建时间
 *  @param success
 *  @param failure
 *  @param progress
 */
- (void)downloadFileWithOption:(NSDictionary *)paramDic
                   withFileUrl:(NSString*)requestURL
                      fileType:(HomeWorkFileType)fileType
                      fileName:(NSString *)fileName
                   fileCreated:(UInt32)created
               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
                      progress:(void (^)(float progress, long long downloadLength, long long totleLength))progress;
{
    //沙盒路径    //NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    
    NSMutableURLRequest *request =[_serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    
    _downLoadOperation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    NSString *localSavePath = [NSString stringWithFormat:@"%@/%@", [self setPathOfDocumentsByFileCreated:created fileName:fileName], fileName];
    
    [_downLoadOperation setOutputStream:[NSOutputStream outputStreamToFileAtPath:localSavePath append:NO]];
    [_downLoadOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        if (progress) {
            progress(p, totalBytesRead, totalBytesExpectedToRead);
        }
    }];
    [_downLoadOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(operation,responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(operation,error);
        }
    }];
    
    [_downLoadOperation start];
}
/**
 *  取消下载,并删除本地已经下载了的部分
 *
 *  @param created  文件在服务器创建的时间
 *  @param fileName 文件的名字
 */
- (void)cancleDownLoadFileWithServiceCreated:(UInt32)created fileName:(NSString *)fileName;
{
    [_downLoadOperation cancel];
    
    // 删除本地文件
    NSString *localSavePath = [NSString stringWithFormat:@"%@/%@", [self setPathOfDocumentsByFileCreated:created fileName:fileName], fileName];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    if ([filemanager fileExistsAtPath:localSavePath]) {
        [filemanager removeItemAtPath:localSavePath error:nil];
    }
}

// 正在下载中
- (BOOL)isDownLoadExecuting
{
    return [_downLoadOperation isExecuting];
}
// 下载暂停
- (void)downLoadPause
{
    [_downLoadOperation pause];
}
// 下载继续
- (void)downLoadResume
{
    [_downLoadOperation resume];
}

在下载之前可以先判断一下文件是否已经保存到本地
· - (BOOL)isSavedFileToLocalWithCreated:(UInt32)created fileName:(NSString *)fileName;

你可能感兴趣的:(iOS 使用AFNetWorking下载文件)