CNLiveUserSettingViewController.m 18.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
//
//  CNLiveUserSettingViewController.m
//  CNLiveScioLive
//
//  Created by CNLive-zxw on 2018/9/25.
//  Copyright © 2018年 CNLive. All rights reserved.
//

#import "CNLiveUserSettingViewController.h"
#import "CNLiveUserSettingTableViewCell.h"
#import "CNLiveUserUpdateViewController.h"
#import "VPImageCropperViewController.h"

@interface CNLiveUserSettingViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate,VPImageCropperDelegate>{
    NSData *_imageData;
    
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *data;
@property (nonatomic, weak) UIButton *loginOutBtn;

@end

@implementation CNLiveUserSettingViewController
static NSString *userSettingTableViewCell = @"CNLiveUserSettingTableViewCell";
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = HEXCOLOR(0xebebeb);
    
    [self setUpNavigationBar];
    [self createUI];
    
}
#pragma mark - UI
- (void)setUpNavigationBar{
    
    self.navigationController.navigationBar.barTintColor = Color_Blue;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    UIButton *headerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
    headerButton.layer.cornerRadius = 2.0;
    headerButton.layer.masksToBounds = true;
    [headerButton setImage:[UIImage imageNamed:@"cnlive_white_back"] forState:UIControlStateNormal];
    [headerButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerButton];
    
    self.navigationItem.title = CustomStr(@"UserSettings");
    
}
- (void)createUI{
    
    [self.view addSubview:self.tableView];
    
    UIButton *loginOut = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginOut addTarget:self action:@selector(loginOutClicked:) forControlEvents:UIControlEventTouchUpInside];
    [loginOut setBackgroundColor:Color_Blue];
    [loginOut.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [loginOut setTitle:CustomStr(@"Logout") forState:UIControlStateNormal];
    [loginOut setTitleColor:HEXCOLOR(0xffffff) forState:UIControlStateNormal];
    loginOut.layer.masksToBounds = YES;
    loginOut.layer.cornerRadius = 6.0;
    [self.view addSubview:loginOut];
    _loginOutBtn = loginOut;
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.offset(300);
        
    }];
    [_loginOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom).with.offset(10);
        make.left.equalTo(self.view.mas_left).with.offset(12);
        make.right.equalTo(self.view.mas_right).with.offset(-12);
        make.height.offset(44);
    }];
    
}
- (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.
 }
 */
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0){
        return 10;
        
    }else if (section == 1){
        return 40;
        
    }
    return 0;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00000001f;
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 3;
        
    }else if (section == 1){
        return 2;
        
    }
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSArray *name = @[@[@"更换昵称", @"更换头像", @"修改登录密码"],@[@"绑定手机号", @"绑定邮箱"]];
    NSArray *name = @[@[CustomStr(@"UpdateNickname"), CustomStr(@"UpdateHead"), CustomStr(@"UpdateLoginPassword")],@[CustomStr(@"BindingPhoneNumber"), CustomStr(@"BindingEmail")]];

    NSArray *type = @[@[@"0", @"1", @"4"],@[@"2", @"3"]];
    
    CNLiveUserSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:userSettingTableViewCell];
    if (!cell) {
        cell = [[CNLiveUserSettingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userSettingTableViewCell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.name = name[indexPath.section][indexPath.row];
    cell.type = type[indexPath.section][indexPath.row];
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 1){
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, 40)];
        headerView.backgroundColor = HEXCOLOR(0xebebeb);
        
        UILabel *relatedInformation = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, MainScreenWidth - 24, 40)];
        relatedInformation.backgroundColor = [UIColor clearColor];
        relatedInformation.textColor = HEXCOLOR(0x333333);
        relatedInformation.font = [UIFont systemFontOfSize:15];
        relatedInformation.text = CustomStr(@"AccountBinding");
        [headerView addSubview:relatedInformation];
        
        return headerView;
    }
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, 10)];
    headerView.backgroundColor = HEXCOLOR(0xebebeb);
    return headerView;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, 0.00000001f)];
    footerView.backgroundColor = HEXCOLOR(0xebebeb);
    return footerView;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0 && indexPath.row == 1){
        UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:NSLocalizedString(CustomStr(@"Cancel"), nil)
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:CustomStr(@"TakingPictures"), CustomStr(@"SelectFromPhoneAlbum"), nil];
        [choiceSheet showInView:self.view];
        choiceSheet.tag = 1000;
        return;
    }
    CNLiveUserUpdateViewController *vc = [CNLiveUserUpdateViewController new];
    //    NSArray *name = @[@[@"更换昵称", @"更换头像", @"修改登录密码"],@[@"绑定手机号", @"绑定邮箱"]];
    NSArray *name = @[@[CustomStr(@"UpdateNickname"), CustomStr(@"UpdateHead"), CustomStr(@"UpdateLoginPassword")],@[CustomStr(@"BindingPhoneNumber"), CustomStr(@"BindingEmail")]];
    vc.navTitle = name[indexPath.section][indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
}
/*
 #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.
 }
 */

#pragma mark - Action
- (void)loginOutClicked:(UIButton *)btn{
    [[ZXWUserInformation shareZXWUserInformation] loginOut];
    
    // 取消第三方平台授权
    [ShareSDK cancelAuthorize:SSDKPlatformTypeWechat];
    [ShareSDK cancelAuthorize:SSDKPlatformTypeQQ];
    [ShareSDK cancelAuthorize:SSDKPlatformTypeSinaWeibo];
    
    [AlertViewTool showHUDAddedToView:self.view text:CustomStr(@"LogoutSuccess") block:^{
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    
}

#pragma mark - Lazy Laoding
- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = HEXCOLOR(0xebebeb);
        _tableView.scrollEnabled = NO;
        [_tableView registerClass:[CNLiveUserSettingTableViewCell class] forCellReuseIdentifier:userSettingTableViewCell];
    }
    return _tableView;
}
#pragma mark - CNLiveUserSystemSDK 修改头像
- (void)uploadAvatarWithImage:(UIImage *)image {
    if (![[Reachability reachabilityForInternetConnection] currentReachabilityStatus]) {
        [AlertViewTool showHUDViewText:CustomStr(@"NetworkiInterruption")];
        return;
    }
    [AlertViewTool showHUDView];
    
    ZXWUserInformation *share = [ZXWUserInformation shareZXWUserInformation];
    NSString *uid = share.model.uid;
    [CNLiveUserSystemCenter uploadIconWithUid:uid icon:image success:^(NSDictionary *result) {
        [AlertViewTool hideHUDView];
        if ([result[@"errorCode"] integerValue] == 0) {
            share.model.faceUrl = result[@"data"][@"faceUrl"];
            [share saveUser_headimgUrlString:result[@"data"][@"faceUrl"]];
            [self.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessful object:nil];
            [AlertViewTool showHUDViewText:[NSString stringWithFormat:@"修改头像%@", result[@"errorMessage"]]];
            
        } else {
            [AlertViewTool showHUDViewText:[NSString stringWithFormat:@"修改头像%@", result[@"errorMessage"]]];
        }
    } failure:^(NSDictionary *errorDic) {
        [AlertViewTool hideHUDView];
        [AlertViewTool showHUDViewText:errorDic[@"errorMessage"]];
    }];
}
#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
        NSLog(@"TO DO");
        UIImage *image = [self imageByScalingAndCroppingForSourceImage:editedImage targetSize:CGSizeMake(160, 160)];
        self->_imageData = UIImagePNGRepresentation(image);
        [self uploadAvatarWithImage:image];
    }];
}
- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark - camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
#define ORIGINAL_MAX_WIDTH 640.0f
#pragma mark - image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

@end