iOS 用户头像选择以及上传服务器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29284809/article/details/50550149

很多时候我们都会遇到用户上传头像功能的实现,具体实现如下:

#pragma mark -tableView代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        if (indexPath.row == 0) {
           //判断手机的系统,8.0以上使用UIAlertController,一下使用UIAlertView
            if (IAIOS8) {

                self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                alert.view.tintColor = [UIColor blackColor];
                //通过拍照上传图片
                UIAlertAction * takingPicAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                    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 * okAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                        UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
                        imagePicker.delegate = self;
                        imagePicker.allowsEditing = YES;
                        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                        [self presentViewController:imagePicker animated:YES completion:nil];
                    }

                }];

                UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

                }];

                [alert addAction:takingPicAction];
                [alert addAction:okAction];
                [alert addAction:cancelAction];
                [self presentViewController:alert animated:YES completion:nil];


            }else{

                UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从手机相册选择", nil];
                [actionSheet showInView:self.view];
            }
         }
}

#pragma mark 调用系统相册及拍照功能实现方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * chosenImage = info[UIImagePickerControllerEditedImage];
    UIImageView * picImageView = (UIImageView *)[self.view viewWithTag:500];
    picImageView.image = chosenImage;
    chosenImage = [self imageWithImageSimple:chosenImage scaledToSize:CGSizeMake(60, 60)];
    NSData * imageData = UIImageJPEGRepresentation(chosenImage, 0.9);
//    [self saveImage:chosenImage withName:@"avatar.png"];
//    NSURL * filePath = [NSURL fileURLWithPath:[self documentFolderPath]];
    //将图片上传到服务器
//    --------------------------------------------------------
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/json", nil];
    NSString * urlString = [NSString stringWithFormat:@"%@appuser/modifyUserIcon",BASE_URL];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity:1];
    [dict setObject:[userDefaults objectForKey:@"user_id"] forKey:@"user_id"];
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //通过post请求上传用户头像图片,name和fileName传的参数需要跟后台协商,看后台要传的参数名
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"img.jpg" mimeType:@"image/jpeg"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //解析后台返回的结果,如果不做一下处理,打印结果可能是一些二进制流数据
        NSError *error;
        NSDictionary * imageDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        //上传成功后更新数据
        self.personModel.adperurl = imageDict[@"adperurl"];
        NSLog(@"上传图片成功0---%@",imageDict);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传图片-- 失败  -%@",error);
    }];
    [picker dismissViewControllerAnimated:YES completion:^{

    }];

}
//用户取消选取时调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

用户选择头像

#import "ViewController.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong)UIImageView *myHeadPortrait;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.myHeadPortrait = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    _myHeadPortrait.backgroundColor = [UIColor magentaColor];
    [self.view addSubview:self.myHeadPortrait];
    [self setHeadPortrait];
}
//  方法:设置头像样式
-(void)setHeadPortrait{
    //  把头像设置成圆形
    self.myHeadPortrait.layer.cornerRadius=self.myHeadPortrait.frame.size.width/2;
    self.myHeadPortrait.layer.masksToBounds=YES;
    //  给头像加一个圆形边框
    self.myHeadPortrait.layer.borderWidth = 1.5f;
    self.myHeadPortrait.layer.borderColor = [UIColor blackColor].CGColor;

    /**
     *  添加手势:也就是当用户点击头像了之后,对这个操作进行反应
     */
    //允许用户交互
    _myHeadPortrait.userInteractionEnabled = YES;

    //初始化一个手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                               action:@selector(alterHeadPortrait:)];

    //给imageView添加手势
    [_myHeadPortrait addGestureRecognizer:singleTap];
}

//  方法:alterHeadPortrait
-(void)alterHeadPortrait:(UITapGestureRecognizer *)gesture{
    /**
     *  弹出提示框
     */
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮:从相册选择,类型:UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //初始化UIImagePickerController
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1:通过相册(呈现全部相册),UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2,通过相机,UIImagePickerControllerSourceTypeCamera
        //获取方法3,通过相册(呈现全部图片),UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑,即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮:拍照,类型:UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样,只是获取方式不同,前面是通过相册,而现在,我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮:取消,类型:UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto,用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    _myHeadPortrait.image = newPhoto;
    [self dismissViewControllerAnimated:YES completion:nil];
}

自定义相机界面

//自定义相机界面
    _picker.showsCameraControls = NO;

    UIToolbar * tool = [[UIToolbar  alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 40, self.view.frame.size.width, 40)];
    tool.barStyle = UIBarStyleBlackTranslucent;
    tool.barTintColor = [UIColor greenColor];

    UIBarButtonItem * cancel = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(touchCancel)];
    cancel.width = self.view.frame.size.width/2;

    UIBarButtonItem * ok = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(touchOk)];
    ok.width = self.view.frame.size.width/2;

    [tool setItems:@[cancel,ok]];
    //把自定义的view添加到UIImagePickerController的layView上
    _picker.cameraOverlayView = tool;

#pragma mark - 取消按钮和确定按钮
- (void)touchCancel
{
    [self.picker dismissViewControllerAnimated:YES completion:^{

    }];
}
- (void)touchOk
{
    [self.picker takePicture];
}

没有更多推荐了,返回首页