更换头像 相机/相册

//
//  PicturesTableViewCell.m
//  WaterProofer
//
//  Created by admin on 2019/9/21.
//  Copyright © 2019 WaterProofer. All rights reserved.
//

#import "PicturesTableViewCell.h"
@import AVFoundation;
@import Photos;

@interface PicturesTableViewCell ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@end
@implementation PicturesTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}
- (IBAction)cameraClick:(UIButton *)sender {
    //调用相册、相机
    [self createCameraOrPhotoAlbum];
}
#pragma mark -- 调用相机、相册
- (void)createCameraOrPhotoAlbum {
    
    __weak typeof(self)wself = self;
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:nil
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *action =
    [UIAlertAction actionWithTitle:@"相册"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
                               [wself createPhotoAlbum];
                           }];
    
    [alert addAction:action];
    UIAlertAction *action1 =
    [UIAlertAction actionWithTitle:@"拍照"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * _Nonnull action) {
                               [wself createCamera];
                           }];
    
    [alert addAction:action1];
    
    UIAlertAction *cancel =
    [UIAlertAction actionWithTitle:@"取消"
                             style:UIAlertActionStyleCancel
                           handler:^(UIAlertAction * _Nonnull action) {
                               
                               
                           }];
    
    [alert addAction:cancel];
    [self.containingViewController presentViewController:alert animated:YES completion:nil];
    
}

- (void)createCamera {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相机权限
        if (granted) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self.containingViewController presentViewController:picker animated:YES completion:^{
                
            }];
        }else{
            [self showRequestErrorTitle:@"请开启相机权限" handler:^(UIAlertAction *action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            
        }
    }];
}
#pragma - mark -选中图片 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //得到图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *newImage = [self croppedImage:image];
    
    //存入相册
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        //存入相册
        UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil);
    } else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        
    }
    
    [self uploadImageWithImagePath:newImage];//去保存图片 -》 上传图片
    [self.containingViewController dismissViewControllerAnimated:YES completion:^{
    
    }];
}
//剪裁图片
- (UIImage *)croppedImage:(UIImage *)image {
    if (image) {
        //解决倒像问题
        UIGraphicsBeginImageContext(image.size);
        [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //裁剪
        CGRect rectMAX = CGRectMake((newImage.size.width-newImage.size.height)/2, 0, newImage.size.height, newImage.size.height);
        CGImageRef subImageRef = CGImageCreateWithImageInRect(newImage.CGImage, rectMAX);
        UIGraphicsBeginImageContext(rectMAX.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextDrawImage(context, CGRectMake(0, 0, newImage.size.height, newImage.size.height), subImageRef);
        UIImage *viewImage = [UIImage imageWithCGImage:subImageRef];
        UIGraphicsEndImageContext();
        CGImageRelease(subImageRef);
        return viewImage;
    }
    return nil;
}
- (void)createPhotoAlbum {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized){
            
            
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self.containingViewController presentViewController:picker animated:YES completion:^{
                
            }];
        }else{
            
            [self showRequestErrorTitle:@"请开启相册权限" handler:^(UIAlertAction *action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }];
            //            UIAlertController *alert =
            //            [UIAlertController alertControllerWithTitle:@"请开启相册权限"
            //                                                message:@"开启路径:设置>隐私>照片>番茄"
            //                                         preferredStyle:UIAlertControllerStyleAlert];
            //
            //            UIAlertAction *action =
            //            [UIAlertAction actionWithTitle:@"确定"
            //                                     style:UIAlertActionStyleDefault
            //                                   handler:nil];
            //
            //            [alert addAction:action];
            //            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}
#pragma mark -- 上传头像
- (void)uploadImageWithImagePath:(UIImage *)image {
     [self.cameraBtn setImage:image forState:UIControlStateNormal];
    __weak typeof(self)weakSelf = self;
    [[WPApiRequest sharedManager] PostBodyRequestWithActionName:@"" andPramater:@{} andImage:@"" succeeded:^(id  _Nonnull responseObject) {
       

    }];
}

@end
View Code
//上传图片
-(void)uploadMostImageWithURLString:(NSString *)URLString
                         parameters:(NSDictionary*)parameters
                        uploadDatas:(NSArray *)uploadDatas
                         uploadName:(NSString *)uploadName
                            success:(void (^)(NSDictionary*dic))success{
    
    //1.管理器
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    //2 设定类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    manager.requestSerializer.timeoutInterval =  20.0f; //超时时间
    [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"app_system"];
    
    NSMutableDictionary*  postDic = [[NSMutableDictionary alloc]init];
    if (parameters) {
        [postDic addEntriesFromDictionary:parameters];
    }
    
    [postDic setObject:[ArtLoginData sharedManager].cityID forKey:@"city_id"];
    [postDic setObject:[ArtLoginData sharedManager].tokenStr forKey:@"token"];

    [postDic setObject:@"2" forKey:@"vtype"];
    if (![[parameters allKeys]containsObject:@"phone"]) {
        [postDic setObject:[ArtLoginData sharedManager].userID forKey:@"phone"];
    }
    
    if (!(uploadDatas.count>0)) {
        [postDic setObject:@"" forKey:@"imageurl"];
    }
    NSString *stringurl=[NSString stringWithFormat:@"%@%@",BASEURL,URLString];
    
    [self showHUD];
    [manager POST:stringurl parameters:postDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        /*
         *  该方法的参数
         1. appendPartWithFileData:要上传的照片[二进制流]
         2. name:对应网站上[upload.php中]处理文件的字段(比如upload)
         3. fileName:要保存在服务器上的文件名
         4. mimeType:上传的文件的类型
         */
            for (int i = 0; i < uploadDatas.count; i++){
                UIImage *image = uploadDatas[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                [formatter setDateFormat:@"yyyyMMddHHmmss"];
                NSString *dateString = [formatter stringFromDate:[NSDate date]];
                NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
                
                [formData appendPartWithFileData:imageData name:uploadName fileName:fileName mimeType:@"image/jpeg"];
            }
        
    }progress:^(NSProgress * _Nonnull uploadProgress) {
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hideHUD];
        ResultModel *model=[ResultModel yy_modelWithDictionary:responseObject];
        if (model.isSuccess) {
            if(success){
                success(responseObject);
            }
        }else{
            [self showToastWithText:model.msg];
        }
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hideHUD];
        if (TBReachability){
            [self showToastWithText:@"连接服务器失败!"];
        }else{
            [self showToastWithText:@"请检查网络连接!"];
        }
    }];
}
RequestApi
NSMutableArray* tempMutArr = [[NSMutableArray alloc]init];
        
        if(_nowArr.count>0) {
            NSMutableDictionary* dic = [[NSMutableDictionary alloc]init];
            [dic setObject:_nowArr forKey:@"key"];
            [dic setObject:@"1" forKey:@"type"];
            [tempMutArr addObject:dic];
        }
        if(_ImageArr.count>0) {
            NSMutableDictionary* dic = [[NSMutableDictionary alloc]init];
            [dic setObject:_ImageArr forKey:@"key"];
            [dic setObject:@"2" forKey:@"type"];
            [tempMutArr addObject:dic];
        }
        if(_construArr.count>0) {
            NSMutableDictionary* dic = [[NSMutableDictionary alloc]init];
            [dic setObject:_construArr forKey:@"key"];
            [dic setObject:@"3" forKey:@"type"];
            [tempMutArr addObject:dic];
        }
        

        if (tempMutArr.count>0) {
            [self upLoadImage:tempMutArr index:0 itemIndex:0];
            
        }




NSMutableArray* cacheArr;//上传的所有图片成功返回的数据
-(void)upLoadImage:(NSArray *)imageArray index:(NSInteger)index itemIndex:(NSInteger)itemIndex{
    
    //    "position": "[{"positionId":"1","positionName":"屋顶","startTime":"2019 - 09 - 11","endTime":"2019 - 10 - 11","leak":"屋顶水落管处漏水","agreementId":"0","standardId":"0"}]"
    //    url 图片url地址
    //    type 图片类型 1.现场图片 2.鸟瞰图 3 施工图 4.产品认证 5.过程控制 6.闭水试验图片
    //    isMainPicture 是否是主图 0 否 1 是 (招工管理列表会用到)
    if (index==0&&itemIndex==0) {
        cacheArr = [[NSMutableArray alloc]init];
    }
    WPWeakSelf
    NSDictionary* itemDic = imageArray[itemIndex];
    NSArray* itemArr = itemDic[@"key"];
    if(index<itemArr.count){
        
        NSData *data = UIImageJPEGRepresentation(itemArr[index],1);
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:@"ios" forKey:@"function"];
        [dic setObject:@"png" forKey:@"type"];
        NSString *headerPicContent=[data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
        [[WPApiRequest sharedManager] PostBodyRequestWithActionName:FtpFileUpload andPramater:dic andImage:headerPicContent succeeded:^(id  _Nonnull responseObject) {
            NSMutableDictionary* resDic = [NSMutableDictionary dictionaryWithDictionary:responseObject];
            [resDic setObject:itemDic[@"type"] forKey:@"type"];
            if (index==0){
                [resDic setObject:@"1" forKey:@"isMainPicture"];
            }else{
                [resDic setObject:@"0" forKey:@"isMainPicture"];
            }
            [cacheArr addObject:resDic];
            [weakSelf upLoadImage:imageArray index:(index+1) itemIndex:itemIndex];
        }];
    }else{
        itemIndex++;
        if (itemIndex<imageArray.count){
            [weakSelf upLoadImage:imageArray index:0 itemIndex:itemIndex];
            
        }else{
            [self showHudAlertMessage:@"上传成功"];
            [MBManager hideAlert];
            
            NSMutableArray* tempMuArr = [[NSMutableArray alloc]init];
            for (int i=0; i<cacheArr.count; i++) {
                NSDictionary* dic = cacheArr[i];
                NSMutableDictionary* tempDic = [[NSMutableDictionary alloc]init];
                [tempDic setObject:dic[@"Info"][@"ftpPath"] forKey:@"url"];
                [tempDic setObject:dic[@"type"] forKey:@"type"];
                [tempDic setObject:dic[@"isMainPicture"]  forKey:@"isMainPicture"];
                [tempMuArr addObject:tempDic];
            }
            NSString *pictureArrStr=[Global gs_jsonStringCompactFormatForNSArray:tempMuArr];
            [_postdic setObject:pictureArrStr   forKey:@"picture"];//图片集合
            if ([_typeStr isEqualToString:
                 @"0"]||[_typeStr isEqualToString:
                         @"2"]){
                [self EngineeringRequest];
            }else{
                [self DomesticRequest];
            }
        }
    }
}
递归上传图片

 

<key>NSCameraUsageDescription</key>

<string>XXXAPP在上传图片的服务中需要访问您的相机</string>

<key>NSPhotoLibraryUsageDescription</key>

<string>XXXAPP在上传图片的服务中需要访问您的相册</string>

转载于:https://www.cnblogs.com/kingstudy/p/11599572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值