iOS-AFNetworking上传和下载(回调下载进度)

释放双眼,带上耳机,听听看~!

1.下载文件

/**
 *  下载文件
 *
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param savedPath  保存 在磁盘的位置
 *  @param success    下载成功回调
 *  @param failure    下载失败回调
 *  @param progress   实时下载进度回调
 */
+ (void)downloadFileWithOption:(NSDictionary *)paramDic requestURL:(NSString*)requestURL savedPath:(NSString*)savedPath progress:(void (^)(float progress))progress downloadSuccess:(void (^)(id responseObject))success downloadFailure:(void (^)(NSError *error))failure
{
    //事例:NSString *savedPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/xxx.zip"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request =[serializer requestWithMethod:@"POST" URLString:requestURL parameters:paramDic error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:savedPath append:NO]];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        float p = (float)totalBytesRead / totalBytesExpectedToRead;
        progress(p);
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        success(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        failure(error);
        
    }];
    
    [operation start];
    
}

2.上传文件

/**
 *  上传文件
 *
 *  @param paramDic   附加post参数
 *  @param requestURL 请求地址
 *  @param fileData   上传的文件
 *  @param success    上传成功回调
 *  @param failure    上传失败回调
 *  @param progress   实时上传进度回调
 */
+ (void)uploadFileWithOption:(NSDictionary *)paramDic requestURL:(NSString*)requestURL fileData:(NSData*)fileData progress:(void (^)(float progress))progress uploadSuccess:(void (^)(id responseObject))success uploadFailure:(void (^)(NSError *error))failure
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    AFHTTPRequestOperation *operation = [manager POST:requestURL parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"filename.jpeg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);
    }];
    
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        float p = (float)totalBytesWritten / totalBytesExpectedToWrite;
        progress(p);
    }];
}

 

人已赞赏
iOS文章

iOS-判断某个时间是否处于某个时间段内

2019-10-31 12:12:45

iOS文章

iOS把jason字符串转化为标注的data(responseObject)类型

2019-10-31 15:13:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索