利用AFNetworking上传用户头像
1.新建一个专门用来上传照片的类UploadIconService
.h文件
#import <Foundation/Foundation.h>
/// 请求成功的Block
typedef void(^RequestSuccess)(id responseObject);
/// 请求失败的Block
typedef void(^RequestFailed)(NSError *error);
/// 上传进度
typedef void (^Progress)(NSProgress *progress);
@interface UploadIconService : NSObject
+ (instancetype)shareUpload;
/**
上传头像
@param image 图像
@param compressionQuality 质量
*/
- (void)upLoadImageWithImage:(UIImage * __nonnull)image
AndRepresentation:(CGFloat)compressionQuality
WithProgress:(Progress)progress
SuccessBlock:(RequestSuccess)success
FailureBlock:(RequestFailed)failure;
@end
.m文件
#import "UploadIconService.h"
@implementation UploadIconService
+ (instancetype)shareUpload{
static UploadIconService *instance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
if(instance == nil)
{
instance = [[self alloc] init];
}
});
return instance;
}
- (void)upLoadImageWithImage:(UIImage * __nonnull)image
AndRepresentation:(CGFloat)compressionQuality
WithProgress:(Progress)progress
SuccessBlock:(RequestSuccess)success
FailureBlock:(RequestFailed)failure{
//[NSDate timeIntervalGetFromNow]
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
// [manger setSecurityPolicy:securityPolicy];
manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpg", nil];
// manger.responseSerializer = [AFHTTPResponseSerializer serializer];//返回的是二进制数据
// manger.requestSerializer = [AFHTTPRequestSerializer serializer];
manger.requestSerializer = [AFJSONRequestSerializer serializer];//这个是默认的,可以不用写
[manger POST:[NSString stringWithFormat:@"%@%@",BASEURL,JsaveLogo] parameters:@{@"token":[GVUserDefaults standardUserDefaults].token} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//在这里处理image,压缩图片质量,裁剪图片大小
// UIImage *uploadimg = [image scaleToSize:CGSizeMake(100, 100)];
// uploadimg = [UIImage compressImage:uploadimg compressRatio:0.9f];
NSData *data = UIImageJPEGRepresentation(image,compressionQuality);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
[formData appendPartWithFileData:data name:@"topic" fileName:fileName mimeType:@"image/jpg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
progress(uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
success(responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
@end
1.1 name与fileName以及mimeType,fileName可以客户端处理命名,这里是获取当前的时间戳来拼接的。
1.2 manger.responseSerializer的acceptableContentTypes
manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpg", nil];
2.在VC中直接调用
WEAKSELF;
[[UploadIconService shareUpload] upLoadImageWithImage:img AndRepresentation:0.6 WithProgress:^(NSProgress *progress) {
dispatch_async(dispatch_get_main_queue(), ^{
[progressView setAlpha:1 - 1.0 * progress.completedUnitCount / progress.totalUnitCount];
});
} SuccessBlock:^(id responseObject) {
header.userInteractionEnabled = YES;
header.image = img;
progressView.hidden = YES;
[weakSelf savePhoto:img andPresentation:0.6];
[weakSelf sendRequest];
} FailureBlock:^(NSError *error) {
header.userInteractionEnabled = YES;
progressView.hidden = YES;
}];
2.1在回调进度,成功或者失败的时候处理一些UI,当上传成功的时候,保存图片到沙盒。
- (void)savePhoto:(UIImage *)photo andPresentation:(CGFloat)presentation{
NSData *imageData = UIImageJPEGRepresentation(photo,presentation);
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * fullPathToFile = [documentsDirectory stringByAppendingString:JUserHeader];
[imageData writeToFile:fullPathToFile atomically:YES];
}
2.2当使用SDWebImage加载图片时把沙盒的这张图片设置成placeHodelImg
[_headerIcon sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[self placeHodelImg]];
- (UIImage *)placeHodelImg{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * fullPathToFile = [documentsDirectory stringByAppendingString:JUserHeader];
// NSLog(@"%@",fullPathToFile);
NSData * data = [NSData dataWithContentsOfFile:fullPathToFile];
UIImage *image;
if (data) {
image = [UIImage imageWithData:data];
}else{
image = [UIImage imageNamed:@"user_header"];
}
return image;
}
这样做图片上传成功是刷新用户的个人信息是头像不会跳动