美文网首页
2018-07-27

2018-07-27

作者: 爱恨的潮汐 | 来源:发表于2018-07-27 09:20 被阅读11次
    //
    //  CXHomeController.m
    //  AiHenDeChaoXi
    //
    //  Created by 爱恨的潮汐 on 2018/3/19.
    //  Copyright © 2018年 AiHenDeChaoXi. All rights reserved.
    //
    
    #import "CXHomeController.h"
    #import "CXTestController.h"
    #import "CXHomeCellModel.h"
    #import "HomeTableViewCell.h"
    #import "HomeHeaderView.h"
    #import "HomeHeaderModel.h"//头部model
    //资讯详情
    #import "ArticleDetailsController.h"
    
    #import "GuidePageGJView.h"
    
    @interface CXHomeController ()<UITableViewDelegate,UITableViewDataSource>
    //测试控制器
    @property(nonatomic,weak) DragEnableButton * buttonTest;
    //创建tableview
    @property (nonatomic,strong) UITableView * tableView;
    @property(nonatomic,strong)HomeHeaderView * headerView;
    @property (nonatomic,assign)NSInteger currentPage;
    @property(nonatomic,strong)NSMutableArray * dataSouce;
    //头部model
    @property(nonatomic,strong)HomeHeaderModel * modelHeader;
    //首页cell
    @property(nonatomic,strong)HomeTableViewCell *cell;
    
    @property (nonatomic,strong)NSArray *headimages;//轮播图数据
    
    //缓存
    @property(nonatomic,strong)NSMutableArray * dataSouceCache;
    
    
    @end
    
    @implementation CXHomeController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        //在最前面创建客服
        [ServiceButton createServiceUI];
        
        
    #pragma mark============== 创建首页UI===============
        
        self.backButton.hidden = YES;
        self.titleNavLabel.text = @"王府资讯";
        
        //初始化
        self.cell = [[HomeTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:nil];
        self.cell.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1000);
        
        
        //先创建头部
        [self headerView];
        
        //创建
        [self tableView];
        
        //刷新加载
        [self refresh];
        
        
        //测试控制器
        [self createTextControllerUI];
        
        
    #pragma mark ========= 判断是否进入登陆界面 =================
        //判断是否登录
        if ([NSString isNULL:SESSIONID]) {
         //进入登陆界面
            CXLoginController * loginVC = [[CXLoginController alloc]init];
            [loginVC setLoginSuccessRefresh:^{
                //客服
                [ServiceButton isHiddenServiceButton:YES];
            
                //先加载缓存,在请求数据
                [self readCache];
            
            }];
            [self.navigationController pushViewController:loginVC animated:NO];
        }else{
            //启动时已经登陆了
            
            //客服
            [ServiceButton isHiddenServiceButton:NO];
            
            
            //先加载缓存,在请求数据
            [self readCache];
            
        }
        
      
        // 监听UITabBarItem被重复点击时的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarDidClick) name:@"LLTabBarDidClickNotification" object:nil];
        
        
        //接收到登陆成功后的通知
          [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receivedLoginSussceNotf) name:@"loginSussceAfterNotice" object:nil];
        
        NSLog(@"用户Id:%@",USERID);//用户Id
        
        //App程序从后台启动==>>进入前台时的通知(删者必死)
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
        
        //程序从前台进入==>>后台
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive) name:UIApplicationWillResignActiveNotification object:nil];
    
    }
    
    //程序从前后台进入==>>前台
    -(void)appWillEnterForeground{
      
    }
    
    //程序从前台进入==>>后台
    -(void)appBecomeActive{
        
        //获取融云消息未读数量
        [self getRCIMMessageNum];
    }
    
    
    //二次点击tabbar的事件,控件在屏幕中才刷新,不然点击其他tabbar也会刷新
    - (void)tabBarDidClick{
        if ([UIView isViewAddWindowUp:self.view]==YES) {
            //必须在主线程,否则会死
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView.mj_header beginRefreshing]; // MJRefresh
            });
        }
    }
    
    
    //先读取缓存在加载数据
    - (void)readCache{
        
    #pragma mark ================获取缓存数据  轮播图数据   ========
        id cacheJsonScroller = [XHNetworkCache cacheJsonWithURL:[NSString stringWithFormat:@"%@%@",GET_VERSION,loadNavigation]];
        self.headimages = cacheJsonScroller;//轮播图
        self.headerView.headimages = self.headimages;//数组传递到头部
        
        
    #pragma mark ================获取缓存数据  资讯数据   ========
        id cacheJson = [XHNetworkCache cacheJsonWithURL:[NSString stringWithFormat:@"%@%@",GET_VERSION,queryMessage]];
        //先移除
        [self.dataSouce removeAllObjects];
        //解析数据
        for (NSDictionary * dicSouce in cacheJson) {
            CXHomeCellModel * model = [[CXHomeCellModel alloc]init];
            [model mj_setKeyValues:dicSouce];
            model.cellHeight = [self.cell getMaxY];
            [self.dataSouce addObject:model];
        }
        [self.tableView reloadData];//刷新表格
        
        
    #pragma mark ============= 正式加载数据 ===============
        //轮播图数据
        [self loadCXDataNav];
        
        //首页数据
        [self loadCXData];
        
    }
    
    
    //创建测试控制器UI
    -(void)createTextControllerUI{
    #pragma mark ================= 测试控制器入口 =================
            //测试控制器入口
            DragEnableButton * buttonTest = [DragEnableButton buttonWithType:UIButtonTypeCustom];
            self.buttonTest = buttonTest;
            buttonTest.frame = CGRectMake(SCREEN_WIDTH-55, SCREEN_HEIGHT-MC_TabbarHeight-210, 50, 50);
            [buttonTest setTitle:@"开发" forState:UIControlStateNormal];
            buttonTest.backgroundColor = MAIN_COLOR;
            buttonTest.layer.cornerRadius = 25;
            buttonTest.titleLabel.font = [UIFont systemFontOfSize:15];
            WeakSelf(self);
            WeakSelf(buttonTest);
            [buttonTest addTapActionTouch:^{
                //这里一定要用点击手势,否则不响应
                //测试控制器
                CXTestController *testVC = [[CXTestController alloc] init];
                testVC.hidesBottomBarWhenPushed = YES;
                [weakself.navigationController pushViewController:testVC animated:YES];
                //关闭高亮
                weakbuttonTest.highlighted = NO;
                //测试枚举
                [testVC testmeiju:ENUM_ViewController895_ActionTypePause];
            }];
            //拖拽
            [buttonTest setDragEnable:YES];
            //吸附
            [buttonTest setAdsorbEnable:YES];
            [[UIApplication sharedApplication].keyWindow addSubview:buttonTest];
    }
    
    
    //收到登陆成功的通知,刷新首页数据
    -(void)receivedLoginSussceNotf{
        //刷新首页
        NSLog(@"首页刷新了");//在回调里处理
        
    }
    
    
    // 上拉下拉刷新
    - (void)refresh {
        //自己封装的MJ刷新
        [DWB_refreshHeader DWB_RefreshHeaderAddview:self.tableView RefreshType:nil refreshHeader:^{
            //数据请求
            _currentPage = 0;
            //轮播图数据
            [self loadCXDataNav];
            
            [self loadCXData];
        }];
        //自己封装的MJ加载
        [DWB_refreshFooter DWB_RefreshFooterAddview:self.tableView refreshFooter:^{
            _currentPage++;
            //数据请求
            [self loadCXData];
        }];
        
    }
    
    
    //获取融云消息未读数量
    -(void)getRCIMMessageNum{
        //获取融云所有的未读消息数
        int chatNum = [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
        //设置桌面消息角标
        [UIApplication sharedApplication].applicationIconBadgeNumber =  chatNum;
    }
    
    
    //请求轮播图数据
    -(void)loadCXDataNav{
        
        NSDictionary * dict =  @{@"moduleCode":@"1"};//展示模块,1 首页
        [CXAFNetworking POST:loadNavigation parameters:dict controller:self type:nil success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqual:@"00"]){
                //数据
                self.headimages = responseObject[@"root"];//轮播图
                self.headerView.headimages = self.headimages;//数组传递到头部
        
                //客服
                [ServiceButton isHiddenServiceButton:NO];
                
    #pragma mark ================(异步)写入/更新缓存数据(只能是json类型,不能使model) ========
                [XHNetworkCache save_asyncJsonResponseToCacheFile:responseObject[@"root"] andURL:[NSString stringWithFormat:@"%@%@",GET_VERSION,loadNavigation] completed:^(BOOL result) {
                    //if(result)  NSLog(@"(异步)写入/更新缓存数据 成功");
                }];
                
            }else{
        
                //其他错误提示
                [AlertCXView AlertCXAlertCenterAllWithController:self Title:nil Message:responseObject[@"errorMsg"] otherItemArrays:@[@"知道啦"] Type:-1 handler:^(NSInteger index) {}];
            }
            
        } failure:^(NSError * _Nullable error) {
          
        }];
    }
    
    
    //请求资讯数据
    -(void)loadCXData{
        
        NSDictionary * dict =  @{@"page.currPage":@(_currentPage),@"page.count":@(3)};
        [CXAFNetworking POST:queryMessage parameters:dict controller:self type:nil success:^(id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqual:@"00"]){
                if (_currentPage==0) {
                    [self.dataSouce removeAllObjects];
                    //缓存的
                    [self.dataSouceCache removeAllObjects];
                }
                if (_currentPage>0 && [responseObject[@"result"] count]==0) {
                    //已经去全部加载完毕
                    dispatch_async(dispatch_get_main_queue(), ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView.mj_footer endRefreshingWithNoMoreData];
                            self.tableView.mj_footer.hidden = NO;
                        });
                    });
                    
                }
                
                //解析数据
                for (NSDictionary * dicSouce in responseObject[@"result"]) {
                    CXHomeCellModel * model = [[CXHomeCellModel alloc]init];
                    [model mj_setKeyValues:dicSouce];
                     model.cellHeight = [self.cell getMaxY];
                    [self.dataSouce addObject:model];
                    
                    //缓存
                    [self.dataSouceCache addObject:dicSouce];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //空白页处理逻辑【封装】
                    [BlankPagesView createAndRemoveBlankUIWithaddSubview:self.tableView AndScroller:self.tableView AndArray:self.dataSouce AndInfo:@"" AndMinY:_headerView.height];
                    
                    //结束刷新
                    [self.tableView endRefresh_DWB];
                    
                    //客服
                    [ServiceButton isHiddenServiceButton:NO];
                
                    [self.tableView reloadData];//刷新表格
                    
                     //此界面Xcode加上断点可能会卡住,单不是崩溃,去掉断点运行就好
    #pragma mark ========= 用户第一次登陆APP进入首页后加载数据完成后,如果是第一次使用就提示引导页================
                    if ([NSString isNULL:GuidePageState]) {
                        //创建引导页
                        GuidePageGJView * guideView = [[GuidePageGJView alloc]init];
                        [[UIApplication sharedApplication].keyWindow addSubview:guideView];
                        [guideView mas_makeConstraints:^(MASConstraintMaker *make) {
                            make.top.left.right.bottom.mas_equalTo(0);
                        }];
                    }
                    
                    
                });
                
                
    #pragma mark ================(异步)写入/更新缓存数据(只能是json类型,不能使model) ========
                [XHNetworkCache save_asyncJsonResponseToCacheFile:self.dataSouceCache andURL:[NSString stringWithFormat:@"%@%@",GET_VERSION,queryMessage] completed:^(BOOL result) {
                    //if(result)  NSLog(@"(异步)写入/更新缓存数据 成功");
                }];
                
                
            }else{
                //结束刷新
                [self.tableView endRefresh_DWB];
                //其他错误提示
                [AlertCXView AlertCXAlertCenterAllWithController:self Title:nil Message:responseObject[@"errorMsg"] otherItemArrays:@[@"知道啦"] Type:-1 handler:^(NSInteger index) {}];
            }
            
        } failure:^(NSError * _Nullable error) {
            //结束刷新
            [self.tableView endRefresh_DWB];
        }];
    }
    
    
    //用Masonry布局tableView的头
    -(HomeHeaderView *)headerView{
        if (!_headerView) {
            //回调头高,在初始化前面
            _headerView = [[HomeHeaderView alloc]init];
            //tableview头部用Masonry自动布局,得到头高
            CGFloat height =  [_headerView getMaxY];
            CGRect frame = _headerView.frame;
            frame.size.height = height;
            _headerView.frame = frame;
            //添加头部
            self.tableView.tableHeaderView = self.headerView;
            
        }
        return _headerView;
    }
    
    
    //tableView懒加载
    - (UITableView *)tableView {
        if (!_tableView) {
            _tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
            _tableView.delegate=self;
            _tableView.dataSource=self;
            _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            //tableview拖动时收起键盘
            // _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
            //去掉分割线
            _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
            [UIView tablevieiOS11:_tableView isHaveTabbar:YES];
            [self.view addSubview:_tableView];
            //布局
            [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(UIEdgeInsetsMake(MC_NavHeight, 0, MC_TabbarHeight, 0));
            }];
        }
        
        return _tableView;
    }
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
        
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.dataSouce.count;
    }
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        CXHomeCellModel * model = self.dataSouce[indexPath.row];
        return model.cellHeight;
    }
    
    -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        
        return 0.01;
    }
    
    //脚
    -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
        return 0.01;
    }
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        NSString *reuseID = @"cellHome";
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if (cell == nil) {
            cell = [[HomeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            cell.backgroundColor = [UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        //传值给cell
        cell.model = self.dataSouce[indexPath.row];
        return cell;
    }
    
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        CXHomeCellModel * model = self.dataSouce[indexPath.row];
        //资讯详情
        ArticleDetailsController * articleVC = [[ArticleDetailsController alloc]init];
        articleVC.messageId = model.messageId;
        [self.navigationController pushViewController:articleVC animated:YES];
       
    }
    
    -(NSMutableArray *)dataSouce{
        if (!_dataSouce) {
            _dataSouce = [NSMutableArray array];
        }
        return _dataSouce;
    }
    
    -(NSMutableArray *)dataSouceCache{
        if (!_dataSouceCache) {
            _dataSouceCache = [NSMutableArray array];
        }
        return _dataSouceCache;
    }
    
    -(void)dealloc{
        
    }
    
    
    
    -(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        
        //打开tabbar
        self.tabBarController.tabBar.hidden = NO;
        
        _buttonTest.hidden = NO;//测试控制器
        
    }
    
    -(void)viewWillDisappear:(BOOL)animated{
        [super viewWillDisappear:animated];
        
        _buttonTest.hidden = YES;//测试控制器
        
        //跟控制器将要消失也要打开tabbar
        self.tabBarController.tabBar.hidden = NO;
      
    }
    
    - (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
    

    相关文章

      网友评论

          本文标题:2018-07-27

          本文链接:https://www.haomeiwen.com/subject/itlwmftx.html