HomeViewController.m 16.0 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
//
//  HomeViewController.m
//  DreamSleep
//
//  Created by peter on 2022/4/1.
//

#import "HomeViewController.h"
#import "DSHomeView.h"
#import "RescuePlanView.h"
#import "FirstLeadAlertView.h"
#import "UserRequestModel.h"
#import "HomeRequestModel.h"
#import "UnityGameController.h"
#import "SafeSleepRequestModel.h"
#import "WhiteNoiseRequestModel.h"
#import "NoisePlayBar.h"
#import "NoisePlayerManager.h"
#import "DailyTaskController.h"
#import "VersionUpdateBox.h"

@interface HomeViewController ()
@property (nonatomic, strong) DSHomeView *homeTV;
@property (nonatomic, strong) RescuePlanView *rescuePlanView;
@property (nonatomic, strong) NoisePlayBar *noisePlayBar;
/// banner列表数据
@property (nonatomic, strong) NSArray *bannerListData;
/// 舒眠课程列表数据
@property (nonatomic, strong) NSArray *safeListData;
/// 助眠音乐列表数据
@property (nonatomic, strong) NSArray *helpListData;
/// 所有白噪音类型数据
@property (nonatomic, strong) NSArray *noiseTypeArr;
/// APP更新弹框
@property (nonatomic, strong) VersionUpdateBox *updateBox;
@property (nonatomic, assign) int update_Way;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // leftItem
    UILabel *leftLab = [UILabel dkLabWithText:@"小梦睡眠" font:BoldFont(24.0)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftLab];
    
    /* rightItem
     UIButton *dailyTaskBtn = [UIButton new];
     [dailyTaskBtn addTarget:self action:@selector(jumpToDailyTaskPage) forControlEvents:UIControlEventTouchUpInside];
     [dailyTaskBtn dk_setImage:DKImagePickerWithNames(@"ic_home_meirirw", @"dk_ic_home_meirirw", @"ic_home_meirirw") forState:UIControlStateNormal];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:dailyTaskBtn];
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     [self addScaleAnimtaionWithView:dailyTaskBtn];
     });
     */
    
    [self.view addSubview:self.homeTV];
    [self.view addSubview:self.noisePlayBar];
    [self.noisePlayBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.bottom.equalTo(self.view).offset(-15);
        make.height.equalTo(@50);
    }];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    // 活动运营弹框(首次启动不弹框,后面每隔24个小时请求后台接口)
    [self promotionAlert];
    // APP首次启动弹框(只出现一次)
    [self showFirstLeadAlertView];
    
    [self requestHomeData];
    
    // 监听主页需要刷新数据通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needUpdate) name:NeedUpdateHomePage object:nil];
    // 监听需要暂停所有白噪音
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pauseAllNoise) name:NeedPauseAllNoise object:nil];
    
#if DSRELEASE == 1
    // 设置初始值
    self.update_Way = -1;
    [self appWillEnterForeground];
    
    // 监听APP回到前台通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
#endif
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([LoginUtils getUserLoginData]) {
        // 自动登录请求(每次APP首页显示的时候调用)
        [UserRequestModel autoLoginRequestWithCompletion:^(UserRequestModel * _Nonnull requestModel) {
            // 自动登录失败,清除本地用户信息并且跳转到登录页面
            if (requestModel.resCode == DSResCodeFail) {
                [LoginUtils clearUserLoginData];
                [LoginUtils jumpToLoginControllerWithTarget:self];
            }
        }];
    }
    
    [self.homeTV.headerView controllerWillAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.homeTV.headerView controllerWillDisAppear];
}

- (void)pauseAllNoise {
    [[NoisePlayerManager sharedNoisePlayerManager] pauseAll];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NeedUpdateHomePage object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NeedPauseAllNoise object:nil];
    
#if DSRELEASE == 1
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
#endif
}

#pragma mark - 先放大,再缩小
- (void)addScaleAnimtaionWithView:(UIView *)view {
    // 放大效果,并回到原位
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    // 速度控制函数,控制动画运行的节奏
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    // 执行时间
    animation.duration = 0.2;
    // 执行次数
    animation.repeatCount = 1;
    // 完成动画后会回到执行动画之前的状态
    animation.autoreverses = YES;
    // 初始伸缩倍数
    animation.fromValue = [NSNumber numberWithFloat:0.9];
    // 结束伸缩倍数
    animation.toValue = [NSNumber numberWithFloat:1.1];
    [view.layer addAnimation:animation forKey:nil];
}

- (void)needUpdate {
    [self.homeTV.mj_header beginRefreshing];
}

#pragma mark - banner、舒眠课程、助眠音乐数据获取
- (void)requestHomeData {
    WS(weakSelf);
    self.homeTV.mj_header = [DSGifHeader headerWithRefreshingBlock:^{
        [weakSelf muiltiRequest];
    }];
    [self.homeTV.mj_header beginRefreshing];
}

- (void)muiltiRequest {
    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_async(group, queue, ^{
        // 获取首页banner数据
        [HomeRequestModel queryBannerListWithCompletion:^(HomeRequestModel * _Nonnull requestModel) {
            if (requestModel.resCode == DSResCodeSuccess) {
                DSLog(@"获取首页banner数据成功...");
                dispatch_semaphore_signal(semaphore);
                self.bannerListData = requestModel.bannerListData;
            } else {
                [self.homeTV.mj_header endRefreshing];
            }
        }];
    });
    dispatch_group_async(group, queue, ^{
        // 获取首页舒眠课程数据
        [SafeSleepRequestModel getCourseListDataWithSubID:6 isHome:YES completion:^(SafeSleepRequestModel * _Nonnull requestModel) {
            if (requestModel.resCode == DSResCodeSuccess) {
                DSLog(@"获取首页舒眠课程数据成功...");
                dispatch_semaphore_signal(semaphore);
                self.safeListData = requestModel.courseListData;
            } else {
                [self.homeTV.mj_header endRefreshing];
            }
        }];
    });
    dispatch_group_async(group, queue, ^{
        // 获取首页助眠音乐数据
        [SafeSleepRequestModel getCourseListDataWithSubID:18 isHome:YES completion:^(SafeSleepRequestModel * _Nonnull requestModel) {
            if (requestModel.resCode == DSResCodeSuccess) {
                DSLog(@"获取首页助眠音乐数据成功...");
                dispatch_semaphore_signal(semaphore);
                self.helpListData = requestModel.courseListData;
            } else {
                [self.homeTV.mj_header endRefreshing];
            }
        }];
    });
    dispatch_group_async(group, queue, ^{
        // 获取白噪音类型请求
        [WhiteNoiseRequestModel queryRelaxWhiteNoiseTypeWithCompletion:^(WhiteNoiseRequestModel * _Nonnull requestModel) {
            if (requestModel.resCode == DSResCodeSuccess) {
                DSLog(@"获取白噪音类型请求成功...");
                dispatch_semaphore_signal(semaphore);
                self.noiseTypeArr = requestModel.noiseTypeArr;
            } else {
                [self.homeTV.mj_header endRefreshing];
            }
        }];
    });
    
    dispatch_group_notify(group, queue, ^{
        // 四个请求对应四次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        // 在这里进行请求后的方法,回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.homeTV.mj_header endRefreshing];
            
            // 更新UI操作
            [self.homeTV refreshBarnner:self.bannerListData];
            [self.homeTV updateCourseMusicCell:CellTypeCourse data:self.safeListData];
            [self.homeTV updateCourseMusicCell:CellTypeMusic data:self.helpListData];
            [self.homeTV updateNoiseAllTypeData:self.noiseTypeArr];
            
            // 重置白噪音播放
            [[NoisePlayerManager sharedNoisePlayerManager] removeAllNoiseAudioCell];
        });
    });
}

#pragma mark - APP首次启动弹框
- (void)showFirstLeadAlertView {
    if (kGetUserDefaultsBOOL(IsFirstAlert)) { return; }
    FirstLeadAlertView *view = [[FirstLeadAlertView alloc] initWithJumpBlock:^(JumpType type) {
        if (type == JumpTypeAI) {
            // 切换到AI睡眠教练标签
            self.tabBarController.selectedIndex = 1;
        } else {
            // 进入快速入眠页面(首页)
            self.tabBarController.selectedIndex = 0;
        }
    }];
    [view show];
}

#pragma mark - 运营活动相关
- (void)promotionAlert {
    if (kGetUserDefaultsBOOL(IsFirstAlert) == NO) {
        return;
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:kPromotionTime isDirectory:nil]) {
        // 缓存文件最近修改日期
        NSDictionary *fileURLAttributes = [[NSURL fileURLWithPath:kPromotionTime] resourceValuesForKeys:[NSArray arrayWithObjects:NSURLContentModificationDateKey, nil] error:nil];
        NSDate *lastModifiedDate = [fileURLAttributes objectForKey:NSURLContentModificationDateKey];
        // 活动更新时效24小时
        NSInteger updateTime = 60 * 60 * 24;
        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-updateTime];
        NSComparisonResult result = [expirationDate compare:lastModifiedDate];
        // 运营活动弹框时机(每天调用1次)
        if (result == NSOrderedDescending) {
            [self queryPromotionImageRequest];
        }
    } else {
        [self queryPromotionImageRequest];
    }
}

- (void)queryPromotionImageRequest {
    [HomeRequestModel queryPromotionImageWithCompletion:^(HomeRequestModel * _Nonnull requestModel) {
        if (requestModel.resCode == DSResCodeSuccess) {
            PromotionModel *pModel = requestModel.promotionModel;
            if (pModel) { [self showRescuePlanView:pModel]; }
        }
    }];
}

- (void)showRescuePlanView:(PromotionModel *)pModel {
    RescuePlanView *rescuePlanView = [[RescuePlanView alloc] initWithJumpBlock:^{
        if (pModel.login_flag == 1) { // 需要用户登录才可以点击进入相应界面
            // 判断是否登录成功
            if ([LoginUtils getUserLoginData]) {
                [self jumpToActiveInterface:pModel];
            } else {
                // 跳转到登录页面
                [LoginUtils jumpToLoginControllerWithTarget:self];
            }
        } else { // 不需要登录也可以进入相应界面
            [self jumpToActiveInterface:pModel];
        }
    } imageUrl:pModel.image_url];
    self.rescuePlanView = rescuePlanView;
    [self.rescuePlanView show];
}

- (void)jumpToActiveInterface:(PromotionModel *)pModel {
    [self.rescuePlanView dismiss];
    WS(weakSelf);
    BOOL isNative = [pModel.page_url containsString:@"native"];
    // 跳转到原生页面
    if (isNative) {
        int type = [[[pModel.page_url componentsSeparatedByString:@"type="] lastObject] intValue];
        if (type == 1) { // AI睡眠教练
            // 切换到AI睡眠教练标签
            self.tabBarController.selectedIndex = 1;
        } else if (type == 2) { // 首页
            self.tabBarController.selectedIndex = 0;
        } else if (type == 3) { // 哄睡页面(未登录就可以进去)
            UnityGameController *gameVC = [UnityGameController new];
            gameVC.gameType = GameTypeCoax;
            [self.navigationController pushViewController:gameVC animated:YES];
        } else if (type == 4) { // 小球游戏(未登录就可以进去)
            UnityGameController *gameVC = [UnityGameController new];
            gameVC.gameType = GameTypeBall;
            [self.navigationController pushViewController:gameVC animated:YES];
        }
    } else {
        // 跳转到H5页面
        [weakSelf.navigationController pushViewController:[[DsWebController alloc] initWithLink:pModel.page_url isShowNavi:NO] animated:YES];
    }
}

#pragma mark - 每日任务相关
- (void)jumpToDailyTaskPage {
    if ([LoginUtils getUserLoginData]) {
        [self.navigationController pushViewController:[DailyTaskController new] animated:YES];
    } else {
        [LoginUtils jumpToLoginControllerWithTarget:self];
    }
}

#pragma mark - APP升级相关
- (void)appWillEnterForeground {
    // 已经是最新版本
    if (self.update_Way == 2) { return; }
    
    if (self.update_Way == -1) {
        // 第一次进入
        [self updateVersionAction];
    } else if (self.update_Way == 0) {
        // 如果是强制更新(APP每次回到前台调用)
        [self updateVersionAction];
    } else if (self.update_Way == 1) {
        if ([self isNeedShowUpdateBox]) {
            [self updateVersionAction];
        } else {
            DSLog(@"一天只能提示用户选择更新1次");
        }
    }
}

- (void)updateVersionAction {
    [VersionRequestModel queryAppVersionRequestWithCompletion:^(VersionRequestModel * _Nonnull requestModel) {
        if (requestModel.resCode == DSResCodeSuccess) {
            self.update_Way = requestModel.update_Way;
            // 本地版本 < 服务器版本
            if ([DSAppVersion compare:requestModel.version_Num options:NSNumericSearch] == NSOrderedAscending) {
                // 服务器返回的是选择更新并且1天内未弹框
                if (self.update_Way == 1 && [self isNeedShowUpdateBox]) {
                    [self.updateBox showWithVersionNum:requestModel.version_Num content:requestModel.version_Content isForce:NO];
                    return;
                }
                // 强制更新
                if (self.update_Way == 0) {
                    [self.updateBox showWithVersionNum:requestModel.version_Num content:requestModel.version_Content isForce:YES];
                }
            } else {
                // 本地版本 >= 服务器版本
                self.update_Way = 2;
            }
        }
    }];
}

- (BOOL)isNeedShowUpdateBox {
    // 用户选择更新(每隔1天触发1次)
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *ageDateString = [dateFormatter stringFromDate:kGetUserDefaultsObj(SelectUpdateTime)];
    NSString *nowDateString = [dateFormatter stringFromDate:[NSDate date]];
    DSLog(@"日期比较之前:%@ 现在:%@", ageDateString, nowDateString);
    
    return ![ageDateString isEqualToString:nowDateString];
}

#pragma mark - 导航栏日间、黑夜模式
- (NaviStyle)navigationBarStyle {
    return [self.dk_manager.themeVersion isEqualToString:DKThemeVersionNormal] ? NaviStyleLight : NaviStyleDark;
}

#pragma mark - lazy
- (DSHomeView *)homeTV {
    if (!_homeTV) {
        _homeTV = [[DSHomeView alloc] init];
    }
    return _homeTV;
}

- (NoisePlayBar *)noisePlayBar {
    if (!_noisePlayBar) {
        _noisePlayBar = [NoisePlayBar new];
    }
    return _noisePlayBar;
}

- (VersionUpdateBox *)updateBox {
    if (!_updateBox) {
        _updateBox = [[VersionUpdateBox alloc] initWithFrame:CGRectZero];
    }
    return _updateBox;
}

@end