上传头像在APP开发中是个很常见的功能,也不难,但是对于没有接触过的小伙伴还是有点坑的,不过只要稍微弄明白了 各个参数的意思就很简单了。直接贴出来代码,简单粗暴。
1 首先因为要用到imagePicker,所以需要先遵守协议
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
2 给头像的ImageView添加个tap手势
这个要记得开userInteractionEnabled,要不点了也没反应
//头像
UITapGestureRecognizer *changeUserIconTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserIconAction:)];
[_user_iconImageView addGestureRecognizer:changeUserIconTap];
2 tap事件里面
//更换头像
- (void)changeUserIconAction:(UITapGestureRecognizer *)tap{
//底部弹出来个actionSheet来选择拍照或者相册选择
UIAlertController *userIconActionSheet = [UIAlertController alertControllerWithTitle:@"请选择上传类型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//相册选择
UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
WKLog(@"相册选择");
//这里加一个判断,是否是来自图片库
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self; //协议
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}];
//系统相机拍照
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
WKLog(@"相机选择");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//取消
WKLog(@"取消");
}];
[userIconActionSheet addAction:albumAction];
[userIconActionSheet addAction:photoAction];
[userIconActionSheet addAction:cancelAction];
[self presentViewController:userIconActionSheet animated:YES completion:nil];
}
代理方法
#pragma mark 调用系统相册及拍照功能实现方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];//获取到所选择的照片
_user_iconImageView.image = img;
UIImage *compressImg = [self imageWithImageSimple:img scaledToSize:CGSizeMake(60, 60)];//对选取的图片进行大小上的压缩
[self transportImgToServerWithImg:compressImg]; //将裁剪后的图片上传至服务器
[self dismissViewControllerAnimated:YES completion:nil];
}
//用户取消选取时调用,可以用来做一些事情
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
图片裁剪压缩方法
//压缩图片方法
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
上传到服务器
//上传图片至服务器后台
- (void)transportImgToServerWithImg:(UIImage *)img{
NSData *imageData;
NSString *mimetype;
//判断下图片是什么格式
if (UIImagePNGRepresentation(img) != nil) {
mimetype = @"image/png";
imageData = UIImagePNGRepresentation(img);
}else{
mimetype = @"image/jpeg";
imageData = UIImageJPEGRepresentation(img, 1.0);
}
NSString *urlString = @"http:///XXXXXX";
NSDictionary *params = @{@"login_token":@"220"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:urlString parameters:paramsconstructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSString *str = @"avatar";
NSString *fileName = [[NSString alloc] init];
if (UIImagePNGRepresentation(img) != nil) {
fileName = [NSString stringWithFormat:@"%@.png", str];
}else{
fileName = [NSString stringWithFormat:@"%@.jpg", str];
}
// 上传图片,以文件流的格式
/**
*filedata : 图片的data
*name : 后台的提供的字段
*mimeType : 类型
*/
[formData appendPartWithFileData:imageData name:str fileName:fileName mimeType:mimetype];
} progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//打印看下返回的是什么东西
WKLog(@"上传凭证成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
WKLog(@"上传图片失败,失败原因是:%@", error);
}];
}
需要注意的一些东西:
1.一定记得在info.plist里面 写获取 相册,相机权限的字段,要不会崩的。
2.拍照只能在真机上试。
3.上传的时候,参数可以加密,但是加密后data可能有变化,这个就需要自己看着办了。。。