上傳頭像在APP開(kāi)發(fā)中是個(gè)很常見(jiàn)的功能,也不難,但是對(duì)于沒(méi)有接觸過(guò)的小伙伴還是有點(diǎn)坑的,不過(guò)只要稍微弄明白了 各個(gè)參數(shù)的意思就很簡(jiǎn)單了。直接貼出來(lái)代碼,簡(jiǎn)單粗暴。
1 首先因?yàn)橐玫絠magePicker,所以需要先遵守協(xié)議
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
2 給頭像的ImageView添加個(gè)tap手勢(shì)
這個(gè)要記得開(kāi)userInteractionEnabled,要不點(diǎn)了也沒(méi)反應(yīng)
//頭像
UITapGestureRecognizer *changeUserIconTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeUserIconAction:)];
[_user_iconImageView addGestureRecognizer:changeUserIconTap];
2 tap事件里面
//更換頭像
- (void)changeUserIconAction:(UITapGestureRecognizer *)tap{
//底部彈出來(lái)個(gè)actionSheet來(lái)選擇拍照或者相冊(cè)選擇
UIAlertController *userIconActionSheet = [UIAlertController alertControllerWithTitle:@"請(qǐng)選擇上傳類型" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//相冊(cè)選擇
UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"手機(jī)相冊(cè)選擇" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
WKLog(@"相冊(cè)選擇");
//這里加一個(gè)判斷,是否是來(lái)自圖片庫(kù)
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self; //協(xié)議
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentViewController:imagePicker animated:YES completion:nil];
}
}];
//系統(tǒng)相機(jī)拍照
UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相機(jī)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
WKLog(@"相機(jī)選擇");
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 調(diào)用系統(tǒng)相冊(cè)及拍照功能實(shí)現(xiàn)方法
- (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)];//對(duì)選取的圖片進(jìn)行大小上的壓縮
[self transportImgToServerWithImg:compressImg]; //將裁剪后的圖片上傳至服務(wù)器
[self dismissViewControllerAnimated:YES completion:nil];
}
//用戶取消選取時(shí)調(diào)用,可以用來(lái)做一些事情
- (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;
}
上傳到服務(wù)器
//上傳圖片至服務(wù)器后臺(tái)
- (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 : 后臺(tái)的提供的字段
*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里面 寫獲取 相冊(cè),相機(jī)權(quán)限的字段,要不會(huì)崩的。
2.拍照只能在真機(jī)上試。
3.上傳的時(shí)候,參數(shù)可以加密,但是加密后data可能有變化,這個(gè)就需要自己看著辦了。。。