AFNetWorking的简单封装 图片音频 视频下载 上传 请求数据

来源:互联网 发布:有些源码上传会失败 编辑:程序博客网 时间:2024/05/13 04:06

第一步,继承AFNetWorking 最新的库
点击下载AFNetWorking

第二步,新建一个类,我们称之为NetWorkTool,继承NSObject

请求方法

声明:

    /**     *  发送一个post请求     *     *  @param url     请求路径     *  @param params  请求参数     *  @param success 请求成功后的回调     *  @param failure 请求失败后的回调     */    + (void)postWithURL:(NSString *)url params:(NSDictionary *)params     success:(void(^)(id responseObject))success     failure:(void(^)(NSError *error))failure;

实现:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];    manager.requestSerializer = [AFHTTPRequestSerializer serializer];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {        if (success) {            NSData *data = [[NSData alloc]initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];            id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];            success(dic);        }    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        if (failure) {            failure(error);        }    }];

上传图片

这里我们imageArr数组保存的应当是UIImage对象
声明:

+ (void)upLoadImageWithOption:(NSDictionary *)para withInferface:(NSString *)requestURL imageArr:(NSArray*)imageArr uploadSuccess:(void (^)(AFHTTPRequestOperation *, id))success uoloadFailure:(void (^)(AFHTTPRequestOperation *, NSError *))failure progress:(void (^)(float))progress

实现:

 AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];    NSMutableURLRequest *requset = [serializer multipartFormRequestWithMethod:@"POST" URLString:requestURL parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        NSInteger i = 0;//此处循环是为了将UIImage对象进行压缩。可不处理直接转为二进制data即可。        for(UIImage *image in imageArr)        {            UIImage *newImage = [VTGeneralTool imageCompressForWidth:image targetWidth:640];            NSData *imageData  = UIImagePNGRepresentation(newImage);            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"picfile%ld",(long)i] fileName:@"image.png" mimeType:@"image/jpeg"];            i++;        }    } error:nil];    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    manager.responseSerializer = [AFHTTPResponseSerializer serializer];    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:requset success:^(AFHTTPRequestOperation *operation, id responseObject) {        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];        success(operation,dict);    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        failure(operation,error);    }];    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {        CGFloat xx = totalBytesExpectedToWrite;        CGFloat yy = totalBytesWritten;        CGFloat pro = yy/xx;        progress(pro);    }];    [operation start];

音视频上传

方法类似图片上传,都是以文件流形式进行传输。
这里对视频上传进行了举列。音频上传不再累述。
声明:

+ (void)upLoadVideoWithOption:(NSDictionary *)para withInferface:(NSString *)requestURL videoPath:(NSURL *)videoURL uploadSuccess:(void (^)(AFHTTPRequestOperation * , id))success uoloadFailure:(void (^)(AFHTTPRequestOperation *, NSError *))failure progress:(void (^)(float))progress

实现:

//此处为对视频进行转码并且压缩为,最终输出为MP4的格式//输出后将文件保存到了/Library/Caches/文件夹内AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];    NSDateFormatter* formater = [[NSDateFormatter alloc] init];    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];    NSString *mp4Path = [NSHomeDirectory() stringByAppendingFormat:@"/Library/Caches/output-%@.mp4", [formater stringFromDate:[NSDate date]]];    exportSession.outputURL = [NSURL fileURLWithPath: mp4Path];    exportSession.outputFileType = AVFileTypeMPEG4;    [exportSession exportAsynchronouslyWithCompletionHandler:^{        switch ([exportSession status]) {            case AVAssetExportSessionStatusFailed:            {                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"错误"                                                                message:[[exportSession error] localizedDescription]                                                               delegate:nil                                                      cancelButtonTitle:@"OK"                                                      otherButtonTitles: nil];                [alert show];                break;            }            case AVAssetExportSessionStatusCancelled:                break;            case AVAssetExportSessionStatusCompleted:            {                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];                //text/plain                manager.responseSerializer = [AFHTTPResponseSerializer serializer];                manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];                AFHTTPRequestOperation *opera = [manager POST:requestURL parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {                    NSData *videoData = [NSData dataWithContentsOfFile:mp4Path];                    [formData appendPartWithFileData:videoData name:@"video000" fileName:@"video000.mp4" mimeType:@"video/mpeg4"];                } success:^(AFHTTPRequestOperation *operation, id responseObject) {                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];                    success(operation,dict);                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {                    failure (operation,error);                }];                [opera setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {                    CGFloat xx = totalBytesExpectedToWrite;                    CGFloat yy = totalBytesWritten;                    CGFloat pro = yy/xx;                    progress(pro);                }];                [opera start];                break;            }            default:                break;        }    }];

文件下载

声明:

+ (void)downloadFileWithOption:(NSDictionary *)paramDic                 withInferface:(NSString*)requestURL                     savedPath:(NSString*)savedPath               downloadSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success               downloadFailure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure                      progress:(void (^)(float progress))progress

实现:

  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);        // NSLog(@"download:%f", (float)totalBytesRead / totalBytesExpectedToRead);//下载进度    }];    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {        success(operation,responseObject);        NSLog(@"下载成功");    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {        success(operation,error);        NSLog(@"下载失败");    }];    [operation start];

第三步:调用
^.^ 直接调用

其他:

图片压缩的方法

+ (UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{    UIImage *newImage = nil;    CGSize imageSize = sourceImage.size;    CGFloat width = imageSize.width;    CGFloat height = imageSize.height;    CGFloat targetWidth = defineWidth;    CGFloat targetHeight = height / (width / targetWidth);    CGSize size = CGSizeMake(targetWidth, targetHeight);    CGFloat scaleFactor = 0.0;    CGFloat scaledWidth = targetWidth;    CGFloat scaledHeight = targetHeight;    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);    if(CGSizeEqualToSize(imageSize, size) == NO){        CGFloat widthFactor = targetWidth / width;        CGFloat heightFactor = targetHeight / height;        if(widthFactor > heightFactor){            scaleFactor = widthFactor;        }        else{            scaleFactor = heightFactor;        }        scaledWidth = width * scaleFactor;        scaledHeight = height * scaleFactor;        if(widthFactor > heightFactor){            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;        }else if(widthFactor < heightFactor){            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;        }    }    UIGraphicsBeginImageContext(size);    CGRect thumbnailRect = CGRectZero;    thumbnailRect.origin = thumbnailPoint;    thumbnailRect.size.width = scaledWidth;    thumbnailRect.size.height = scaledHeight;    [sourceImage drawInRect:thumbnailRect];    newImage = UIGraphicsGetImageFromCurrentImageContext();    if(newImage == nil){        NSLog(@"scale image fail");    }    UIGraphicsEndImageContext();    return newImage;}


文/五阿哥永琪(简书作者)
原文链接:http://www.jianshu.com/p/2919c0ddda49
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
0 0
原创粉丝点击