// // LDMyWechatViewController.m // YouHuiProject // // Created by 小花 on 2018/8/9. // Copyright © 2018年 kuxuan. All rights reserved. // #import "LDMyWechatViewController.h" #import "STPhotoKitController.h" #import "UIImagePickerController+ST.h" #import @interface LDMyWechatViewController () { UIButton *_complete; UILabel *_desLabel; NSURLSessionUploadTask *_uploadTask; NSString *_changeImgUrl; UIImage *_selectImg; BOOL selectedImg; } @property (nonatomic, strong) UITextField *textField; @property (nonatomic, strong) UIButton *switchBtn; @property (nonatomic, strong) UIImageView *imgView; @property (nonatomic, strong) UILabel *textLb; @property (nonatomic, strong) UIActivityIndicatorView *indicatorView; @end @implementation LDMyWechatViewController - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [LoadingView dismiss]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; } - (void)viewDidLoad { [super viewDidLoad]; [self configNavigationBar]; [self initSubUI]; [self request]; } - (void)configNavigationBar { [self.navigationBar setNavTitle:@"我的微信号"]; self.navigationBar.backgroundColor = [UIColor changeColor]; self.navigationBar.navTitleLabel.textColor = [UIColor whiteColor]; UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; [leftBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal]; [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside]; [self.navigationBar setCustomLeftButtons:@[leftBtn]]; self.view.backgroundColor = [UIColor yhGrayColor]; } - (void)backAction { [self.navigationController popViewControllerAnimated:YES]; } - (void)initSubUI { // UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, NavBarHeight+15, 10, 25)]; // label.textColor = [UIColor YHColorWithHex:0x333333]; // label.font = [UIFont systemFontOfSize:Fitsize(16)]; // label.text = @"我的微信号:"; // [label sizeToFit]; // [self.view addSubview:label]; self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, NavBarHeight+Fitsize(70), Fitsize(170), Fitsize(170))]; self.imgView.backgroundColor = [UIColor whiteColor]; self.imgView.centerX = self.view.width/2; self.imgView.userInteractionEnabled = YES; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)]; [self.imgView addGestureRecognizer:tap]; [self.imgView addSubview:self.indicatorView]; [self.view addSubview:self.imgView]; UILabel *textLb = [[UILabel alloc] initWithFrame:CGRectMake(0, self.imgView.bottom+7, SCREEN_WIDTH, 20)]; textLb.font = [UIFont systemFontOfSize:13]; textLb.textColor = [UIColor YHColorWithHex:0x6E6E6E]; textLb.text = @"点击上传微信二维码"; textLb.textAlignment = NSTextAlignmentCenter; self.textLb = textLb; [self.view addSubview:textLb]; UIView *fieldbg = [[UIView alloc] initWithFrame:CGRectMake(0, self.textLb.bottom+Fitsize(100), SCREEN_WIDTH, 50)]; fieldbg.backgroundColor = [UIColor clearColor]; UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 60, 25)]; title.text = @"微信号"; title.font = [UIFont systemFontOfSize:16]; title.textColor = [UIColor YHColorWithHex:0x333333]; [fieldbg addSubview:title]; [self.view addSubview:fieldbg]; self.textField = [[UITextField alloc] initWithFrame:CGRectMake(title.right,0, SCREEN_WIDTH-140, 33)]; self.textField.centerY = title.centerY; self.textField.font = [UIFont systemFontOfSize:14]; self.textField.textColor = [UIColor YHColorWithHex:0x6E6E6E]; self.textField.backgroundColor = [UIColor clearColor]; self.textField.keyboardType = UIKeyboardTypeASCIICapable; self.textField.placeholder = @"请输入微信号,方便下级联系"; self.textField.clearButtonMode = UITextFieldViewModeAlways; [fieldbg addSubview:self.textField]; UIView *line = [[UIView alloc] initWithFrame:CGRectMake(40, self.textField.bottom+5, SCREEN_WIDTH-80, 1)]; line.backgroundColor = [UIColor YHColorWithHex:0x979797]; [fieldbg addSubview:line]; // self.switchBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-15-60, 0, 60, 30)]; // self.switchBtn.centerY = self.textField.centerY; // [self.switchBtn setImage:[UIImage imageNamed:@"yincang"] forState:UIControlStateNormal]; // [self.switchBtn setImage:[UIImage imageNamed:@"gongkai"] forState:UIControlStateSelected]; // [self.switchBtn addTarget:self action:@selector(changeButtonClick:) forControlEvents:UIControlEventTouchUpInside]; // [self.view addSubview:self.switchBtn]; // // UILabel *desLb = [[UILabel alloc] initWithFrame:CGRectMake(10, self.textField.bottom+10, SCREEN_WIDTH-30, 20)]; // desLb.textColor = [UIColor YHColorWithHex:0x999999]; // desLb.font = [UIFont systemFontOfSize:Fitsize(11)]; // desLb.text = @"填写微信号后,您可以选择公开此信息,方便下级联系您"; // _desLabel = desLb; // [self.view addSubview:desLb]; UIButton *complete = [[UIButton alloc] initWithFrame:CGRectMake(0, fieldbg.bottom+33, SCREEN_WIDTH-80, Fitsize(40))]; complete.backgroundColor = [UIColor homeRedColor]; [complete setTitle:@"完成" forState:UIControlStateNormal]; complete.titleLabel.font = [UIFont systemFontOfSize:Fitsize(15)]; [complete setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [complete addTarget:self action:@selector(completeAction) forControlEvents:UIControlEventTouchUpInside]; complete.layer.cornerRadius = 6; complete.backgroundColor = [UIColor homeRedColor]; complete.centerX = self.view.centerX; _complete = complete; [self.view addSubview:complete]; } - (void)tapImageView:(UITapGestureRecognizer *)tap { [self editImageSelected]; } #pragma mark - --- event response 事件相应 --- - (void)editImageSelected { UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [controller setDelegate:self]; controller.modalPresentationStyle = UIModalPresentationFullScreen; if ([controller isAvailablePhotoLibrary]) { [self presentViewController:controller animated:YES completion:^{ [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault]; }]; }else { UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有开启访问相册权限" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { [alertController dismissViewControllerAnimated:YES completion:nil]; [self gotoSetting]; }]; UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [alertController dismissViewControllerAnimated:YES completion:nil]; }]; [alertController addAction:action1]; [alertController addAction:action2]; alertController.modalPresentationStyle = UIModalPresentationFullScreen; [self presentViewController:alertController animated:YES completion:nil]; } } - (void)gotoSetting { NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; if([[UIApplication sharedApplication]canOpenURL:url] ) { if (@available(iOS 10.0, *)) { [[UIApplication sharedApplication] openURL:url options:@{}completionHandler:^(BOOL success) { }]; } else { [[UIApplication sharedApplication]openURL:url]; } } } #pragma mark - 2.UIImagePickerController的委托 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:^{ UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage]; STPhotoKitController *photoVC = [STPhotoKitController new]; [photoVC setDelegate:self]; [photoVC setImageOriginal:imageOriginal]; [photoVC setSizeClip:CGSizeMake(Fitsize(300), Fitsize(300))]; photoVC.modalPresentationStyle = UIModalPresentationFullScreen; [self presentViewController:photoVC animated:YES completion:nil]; }]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:^(){ }]; } - (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage { _selectImg = resultImage; selectedImg = YES; self.imgView.image = resultImage; } - (void)upLoadImage:(UIImage *)image { NSString *url = [NSString stringWithFormat:@"%@/api/v2/adzone/addQrcode",BaseURL]; /* 创建网络请求对象 */ AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager]; /* 设置请求和接收的数据编码格式 */ mgr.requestSerializer = [AFJSONRequestSerializer serializer]; // 设置请求数据为 JSON 数据 mgr.responseSerializer = [AFJSONResponseSerializer serializer]; // 设置接收数据为 JSON 数据 /* 设置请求头 */ mgr.requestSerializer.timeoutInterval = 10; NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary]; NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"]; [mgr.requestSerializer setValue:app_Version forHTTPHeaderField:@"version"]; [mgr.requestSerializer setValue:Channel_id forHTTPHeaderField:@"source"]; [mgr.requestSerializer setValue:@"ios" forHTTPHeaderField:@"platform"]; if ([AccountTool isLogin]) { NSString *token = [AccountTool account].token; // NSLog(@"%@",token); [mgr.requestSerializer setValue:token forHTTPHeaderField:@"token"]; } NSString *deviceUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; NSString *uuid = [NSString stringWithFormat:@"I-%@",deviceUUID]; [mgr.requestSerializer setValue:uuid forHTTPHeaderField:@"idfa"]; [mgr POST:url parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) { NSData *data = UIImageJPEGRepresentation(image,1); NSString *name = [self getNowTimeTimestamp]; NSString *fileName = [NSString stringWithFormat:@"%@.png",name]; [formData appendPartWithFileData:data name:@"img" fileName:fileName mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { if (uploadProgress) { CGFloat progress = uploadProgress.completedUnitCount/uploadProgress.totalUnitCount; [SVProgressHUD showProgress:progress status:@"图片上传中..."]; } } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { _changeImgUrl = responseObject[@"rst"][@"img"]; self.imgView.image = image; [SVProgressHUD dismiss]; [self requestCompleteWith:_changeImgUrl]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSData * data = error.userInfo[@"com.alamofire.serialization.response.error.data"]; NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"服务器的错误原因:%@",str); [SVProgressHUD dismiss]; [MBProgressHUD showMessage:@"上传失败"]; }]; } - (void)request { [self.indicatorView startAnimating]; NSString *url = [NSString stringWithFormat:@"%@/api/v2/adzoneCreate/displayWeChat",BaseURL]; [LDHttp post:url params:nil success:^(id json) { NSString *wechat; NSString *str = json[@"weChat"]; NSString *qrcode = json[@"qrcode"]; if (str.length > 0) { wechat = [NSString stringWithFormat:@"%@",json[@"weChat"]]; self.textField.text = wechat; }else { self.textField.placeholder = @"请输入微信号,方便下级联系"; } if (qrcode.length > 0) { [self.imgView sd_setImageWithURL:[NSURL URLWithString:qrcode] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) { [self.indicatorView stopAnimating]; }]; selectedImg = YES; }else { self.imgView.image = [UIImage imageNamed:@"addImg"]; [self.indicatorView stopAnimating]; } // [self addRacObserver:wechat]; } failure:^(NSError *error) { [self.indicatorView stopAnimating]; }]; } // //- (void)addRacObserver:(NSString *)wechat { // RACSignal *textSingal = [self.textField.rac_textSignal map:^id(NSString * value) { // BOOL first = value.length > 0; // BOOL second = self.imgView.image != [UIImage imageNamed:@"addImg"]; // BOOL succ = first && second; // return @(succ); // }]; // // // // [textSingal subscribeNext:^(NSNumber *textActionSignal) { // _complete.backgroundColor = textActionSignal.boolValue?[UIColor homeRedColor]:[UIColor lightGrayColor]; // _complete.enabled = textActionSignal.boolValue; // }]; //} //- (void)changeButtonClick:(UIButton *)sender { // [LoadingView show]; // sender.enabled = NO; // NSString *url = [NSString stringWithFormat:@"%@/api/v2/adzoneCreate/openFlag",BaseURL]; // NSNumber *state = sender.selected?@0:@1; // NSDictionary *para = @{@"openStat":state}; // [LDHttp post:url params:para success:^(id json) { // sender.enabled = YES; // if ([json[@"flag"] boolValue]) { // sender.selected = !sender.selected; // NSString *text = sender.selected?@"您的微信号已公开,下级可以看到了":@"您的微信号已关闭,点击按钮公开"; // _desLabel.text = text; // }else { // [MBProgressHUD showMessage:json[@"msg"]]; // } // // [LoadingView dismiss]; // } failure:^(NSError *error) { // [LoadingView dismiss]; // }]; //} - (void)completeAction { if (self.textField.text.length == 0 && !selectedImg) { [MBProgressHUD showMessage:@"请输入微信号或上传二维码"]; return; } if (selectedImg) { [self upLoadImage:self.imgView.image]; }else { [self requestCompleteWith:nil]; } } - (void)requestCompleteWith:(NSString *)newQRUrl { _complete.enabled = NO; NSString *url = [NSString stringWithFormat:@"%@/api/v2/adzoneCreate/addWeChat",BaseURL]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; if (newQRUrl) { [dict setObject:newQRUrl forKey:@"imgUrl"]; }else { [dict setObject:@"" forKey:@"imgUrl"]; } if (self.textField.text.length > 0) { [dict setObject:self.textField.text forKey:@"weChat"]; }else { [dict setObject:@"" forKey:@"weChat"]; } [LDHttp post:url params:dict success:^(id json) { _complete.enabled = YES; [MBProgressHUD showMessage:json[@"msg"]]; if ([json[@"flag"] boolValue]) { [self backAction]; } } failure:^(NSError *error) { _complete.enabled = YES; [MBProgressHUD showMessage:@"加载失败"]; }]; } - (UIActivityIndicatorView *)indicatorView { if (!_indicatorView) { _indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)]; _indicatorView.frame= CGRectMake(0, 0, 50, 50); _indicatorView.color = [UIColor homeRedColor]; _indicatorView.center = CGPointMake(self.imgView.width/2, self.imgView.height/2); _indicatorView.hidesWhenStopped = YES; } return _indicatorView; } - (NSString *)getNowTimeTimestamp{ NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a=[dat timeIntervalSince1970]; NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型 ; return timeString; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end