// // TPOffLineDownLoadController.m // ThePaperDemo // // Created by scar1900 on 14/11/25. // Copyright (c) 2014年 scar1900. All rights reserved. // #import "TPOffLineDownLoadController.h" #import "blueButton.h" #import "offlineDownLoadCell.h" #import "offlineContentController.h" #import "Reachability.h" @interface TPOffLineDownLoadController () { BOOL beginToDownload; } @property(nonatomic, strong)NSMutableArray *dataList; @property(nonatomic, strong)UIView *offlineDownloadTableView; @property(nonatomic, strong)UIButton *downloadBtn; @property(nonatomic, strong)UIButton *clearCacheBtn; @property(nonatomic, strong)NSMutableArray *dataSourceList; @property(nonatomic, strong)NSMutableArray *progressViewList; @end @implementation TPOffLineDownLoadController @synthesize dataList = _dataList; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor colorWithHexString:BackGroundColor]; [self.view addSubview:self.offlineDownloadTableView]; [self.view addSubview:self.downloadBtn]; [self.view addSubview:self.clearCacheBtn]; beginToDownload = NO; self.dataList = [NSMutableArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; [self checkIfAllCellUnselected]; [self.downloadBtn makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.view.left).offset(10); make.right.equalTo(self.view.centerX).offset(-5/2); make.top.equalTo(self.offlineDownloadTableView.bottom).offset(60); make.height.equalTo(@40); }]; [self.clearCacheBtn makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.view.centerX).offset(5/2); make.right.equalTo(self.view.right).offset(-10); make.top.equalTo(self.offlineDownloadTableView.bottom).offset(60); make.height.equalTo(@40); }]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(remoteQueFinished) name:QUEDIDFINISH object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needrefreshNightMode:) name:REFRESHAFTERNIGHTMODE object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; } - (void) reachabilityChanged:(NSNotification *)note { if (beginToDownload) { [Remote pauseUrlSessionURLDownload]; } if (![Remote IsEableNetwork]) { if (beginToDownload) { ShowTextMessage(@"网络连接失败,暂停下载!"); [self.clearCacheBtn setEnabled:YES]; [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = NO; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } }else { if (beginToDownload) { if (![Remote IsEnableWIFI]) { UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"" message:@"现在正使用手机网络,继续使用可能会产生相关流量使用费用,是否继续下载?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil]; alert1.tag = 1000; [alert1 show]; }else { [self.clearCacheBtn setEnabled:NO]; [self.downloadBtn setTitle:@"暂停下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = YES; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } } } } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.titleStr = @"离线阅读"; [TPUserDefault instance].isOffline = YES; } - (void)resetProgressViewInList { BOOL isFirstAdd = NO; if (!self.progressViewList) { self.progressViewList = [NSMutableArray array]; isFirstAdd = YES; } [self.dataList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { // }] // [self.dataList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { offlineDownLoadCell *cell = nil; offlineDownLoadCell *lastCell = nil; if (isFirstAdd) { cell = [[offlineDownLoadCell alloc]initWithFrame:CGRectZero]; [self.progressViewList addObject:cell]; cell.delegate = self; }else { cell = [self.progressViewList objectAtIndex:idx]; } cell.dataDic = [NSMutableDictionary dictionaryWithDictionary:self.dataList[idx]]; cell.isBeginToDownload = beginToDownload; if (idx != 0) { lastCell = [self.progressViewList objectAtIndex:idx-1]; } if (isFirstAdd) { [self.offlineDownloadTableView addSubview:cell]; [self.offlineDownloadTableView makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.view.left); make.right.equalTo(self.view.right); make.top.equalTo(self.naviBar.bottom); make.height.mas_equalTo(60*self.dataList.count); }]; if (lastCell) { [cell makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(lastCell.bottom); make.height.mas_equalTo(60); }]; }else { [cell makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(self.offlineDownloadTableView.top); make.height.mas_equalTo(60); }]; } }else { NSString *isSelectStr = obj[@"isSelected"]; if (lastCell) { [cell remakeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(lastCell.bottom); make.height.mas_equalTo(60); }]; }else { [cell remakeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(self.offlineDownloadTableView.top); make.height.mas_equalTo(60); }]; } if ([isSelectStr intValue] != 1) { if (beginToDownload) { if (lastCell) { [cell remakeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(lastCell.bottom); make.height.mas_equalTo(0); }]; }else { [cell remakeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.offlineDownloadTableView.left); make.right.equalTo(self.offlineDownloadTableView.right); make.top.equalTo(self.offlineDownloadTableView.top); make.height.mas_equalTo(0); }]; } } } } }]; } #pragma mark - set and get method - (void)setDataList:(NSMutableArray *)list { _dataList = list; } - (void)setDataSourceList:(NSMutableArray *)list { if (beginToDownload) { NSMutableArray *temp = [NSMutableArray array]; [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj[@"isSelected"] intValue] == 1 || [obj[@"isFinish"] intValue] == 1) { [temp addObject:obj]; } }]; _dataSourceList = temp; }else { _dataSourceList = list; } [self resetProgressViewInList]; } - (UIView *)offlineDownloadTableView { if (!_offlineDownloadTableView) { _offlineDownloadTableView = [[UIView alloc]initWithFrame:CGRectZero]; // _offlineDownloadTableView.separatorStyle = UITableViewCellSeparatorStyleNone; // _offlineDownloadTableView.backgroundColor = [UIColor colorWithHexString:CELLBACKCOLOR]; // _offlineDownloadTableView.delegate = self; // _offlineDownloadTableView.dataSource = self; // _offlineDownloadTableView.scrollEnabled = NO; } return _offlineDownloadTableView; } - (UIButton*)downloadBtn { if (!_downloadBtn) { _downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_downloadBtn.layer setCornerRadius:8.0f]; [_downloadBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:BLUECOLOR]) forState:UIControlStateNormal]; [_downloadBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:BUTTONSELECTBACK]) forState:UIControlStateHighlighted]; _downloadBtn.clipsToBounds = YES; [_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [_downloadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected]; [_downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [_downloadBtn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; } _downloadBtn.titleLabel.font = appFont(33.2/2, NO); return _downloadBtn; } - (UIButton*)clearCacheBtn { if (!_clearCacheBtn) { _clearCacheBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_clearCacheBtn.layer setCornerRadius:8.0f]; [_clearCacheBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:BLUECOLOR]) forState:UIControlStateNormal]; [_clearCacheBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:BUTTONSELECTBACK]) forState:UIControlStateHighlighted]; _clearCacheBtn.clipsToBounds = YES; [_clearCacheBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [_clearCacheBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected]; [_clearCacheBtn setTitle:@"删除缓存" forState:UIControlStateNormal]; [_clearCacheBtn addTarget:self action:@selector(clearDownloadCache:) forControlEvents:UIControlEventTouchUpInside]; } _clearCacheBtn.titleLabel.font = appFont(33.2/2, NO); return _clearCacheBtn; } #pragma mark - button handler - (void)downLoad:(UIButton*)btn { if ([btn.titleLabel.text isEqualToString:@"开始下载"]) { if (![Remote IsEableNetwork]) { ShowTextMessage(@"网络连接中断,请检查网络设置!"); /** * bug:5031(离线下载:无网络状态开始下载状态判断有问题) */ return; } if (![Remote IsEnableWIFI]) { UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"" message:@"确定使用手机流量下载?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil]; alert1.tag = 1000; [alert1 show]; return; } [self beginDownload]; } } - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (alertView.tag == 1000) { if (buttonIndex != 0) { [self beginDownload]; }else { [self.clearCacheBtn setEnabled:YES]; [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = NO; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } }else { if (buttonIndex != 0) { /** * bug:5311(删除离线阅读文章,弹出“是否确定删除离线数据”点击取消时,仍然删除) */ [self performSelectorOnMainThread:@selector(startWaitCursor:) withObject:nil waitUntilDone:YES]; NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:ConfigPath(@"")]; __block BOOL noCacheToClear = YES; for (NSString *p in files) { NSArray *tempArray = [NSArray arrayWithArray:self.dataList]; NSMutableArray *tempDataList = [NSMutableArray arrayWithArray:tempArray]; [tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSString *fileName = obj[@"fileName"]; // NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:[TPUserDefault instance].pauseDataDic]; if ([obj[@"isSelected"] intValue] == 1) { NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithDictionary:obj]; [dic setValue:nil forKey:@"updateDate"]; [dic setValue:nil forKey:@"resData"]; [dic setValue:@"0" forKey:@"isFinish"]; [dic setValue:@"0" forKey:@"currentByte"]; NSString *pathName = [fileName stringByReplacingOccurrencesOfString:@".zip" withString:@""]; if (fileName && [p isMatchedByRegex:pathName]) { NSError *error; NSString *path = [ConfigPath(@"") stringByAppendingString:p]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { TPLOG(@"%@",path); noCacheToClear = NO; [[NSFileManager defaultManager] removeItemAtPath:path error:&error]; } } [tempDataList replaceObjectAtIndex:idx withObject:dic]; } }]; self.dataList = [NSMutableArray arrayWithArray:tempDataList]; } [TPUserDefault instance].offlineStatusList = self.dataList; beginToDownload = NO; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; [self performSelectorOnMainThread:@selector(stopWaitCursor:) withObject:nil waitUntilDone:YES]; [TPUserDefault instance].pauseDataDic = [NSMutableDictionary dictionary]; if (noCacheToClear && ![Remote clearPartialDataCache]) { ShowTextMessage(@"没有离线数据"); }else { ShowTextMessage(@"删除离线数据成功"); } } } } - (void)beginDownload { TPLOG(@"开始下载!"); if (isIOS7) { }else { [Remote resetRemoteQueue]; } [self.clearCacheBtn setEnabled:NO]; [self.downloadBtn setTitle:@"暂停下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = YES; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } - (void)pauseDownLoad:(UIButton*)btn { if ([btn.titleLabel.text isEqualToString:@"暂停下载"]) { TPLOG(@"暂停下载!"); [self.clearCacheBtn setEnabled:YES]; if (isIOS7) { [Remote pauseUrlSessionURLDownload]; }else { [Remote pauseQueue]; } [_downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [btn removeTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; [btn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = NO; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } } - (void)downLoadFinishOrStop { TPLOG(@"结束下载!"); [self.clearCacheBtn setEnabled:YES]; [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = NO; [Remote clearPartialDataCache]; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } - (void)clearDownloadCache:(UIButton*)btn { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"是否确认删除离线数据?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil]; alert.tag = 1001; [alert show]; /** * bug:5124(离线阅读中删除已换缓存的新闻,没有“是否确定删除”的提示框) */ } //#pragma mark - tableView delegate and datasource //- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // return 1; //} // //- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // return self.dataSourceList.count; //} // //- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // return 60; //} // //- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // static NSString *offlineDownloadCellIdentifer = @"offlineDownloadCellIdentifer"; // offlineDownLoadCell *cell = (offlineDownLoadCell*)[tableView dequeueReusableCellWithIdentifier:offlineDownloadCellIdentifer]; // if (nil == cell) { // cell = [[offlineDownLoadCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:offlineDownloadCellIdentifer]; // } // cell.dataDic = [NSMutableDictionary dictionaryWithDictionary:self.dataSourceList[indexPath.row]]; // cell.isBeginToDownload = beginToDownload; // cell.delegate = self; // return cell; //} - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; offlineDownLoadCell *cell = (offlineDownLoadCell*)[tableView cellForRowAtIndexPath:indexPath]; NSDictionary *dic = cell.dataDic; if (dic[@"resData"]) { offlineContentController *vc = [offlineContentController new]; vc.resData = dic[@"resData"]; vc.path= dic[@"path"]; [TPUserDefault instance].offlinePath = dic[@"path"]; TPLOG(@"%@",dic[@"path"]); [self.navigationController pushViewController:vc animated:YES]; }else { ShowTextMessage(@"没有离线数据,请先下载"); } } - (void)clickCell:(NSMutableDictionary *)dic { if (dic[@"resData"]) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ offlineContentController *vc = [offlineContentController new]; vc.resData = dic[@"resData"]; vc.path= dic[@"path"]; [TPUserDefault instance].offlinePath = dic[@"path"]; TPLOG(@"%@",dic[@"path"]); [self.navigationController pushViewController:vc animated:YES]; [TPUserDefault instance].isOffline = YES; }); }else { ShowTextMessage(@"没有离线数据,请先下载"); } } #pragma mark - offlineCellDelegate - (void)updateDataList:(NSMutableDictionary *)newDataDic { if (beginToDownload) { return; } /** * bug:5118( 离线缓存: 两个以上栏目同时下载,其中一个下载好后点击删除缓存,出现异常) */ NSArray *tempArray = [NSArray arrayWithArray:self.dataList]; [tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([newDataDic[@"nodeId"] isEqualToString:obj[@"nodeId"]]) { [self.dataList replaceObjectAtIndex:idx withObject:newDataDic]; } }]; [TPUserDefault instance].offlineStatusList = self.dataList; [self checkIfAllCellUnselected]; } - (void)simpleUpdateDataList:(NSMutableDictionary *)newDataDic { NSArray *tempArray = [NSArray arrayWithArray:self.dataList]; [tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([newDataDic[@"nodeId"] isEqualToString:obj[@"nodeId"]]) { [self.dataList replaceObjectAtIndex:idx withObject:newDataDic]; } }]; __block BOOL isFinish = YES;; [self.dataList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { if ([obj[@"isSelected"] intValue]==1 && !obj[@"resData"]) { isFinish = NO; *stop = YES; } }]; if (isFinish) { [TPUserDefault instance].offlineStatusList = self.dataList; [self checkIfAllCellUnselected]; } } - (void)noOfflineDataInRemote:(NSMutableDictionary *)newDataDic { NSArray *tempArray = [NSArray arrayWithArray:self.dataList]; [tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([newDataDic[@"nodeId"] isEqualToString:obj[@"nodeId"]]) { [self.dataList replaceObjectAtIndex:idx withObject:newDataDic]; } }]; [self checkIfNoOfflineData]; } - (void)checkDownloadUrlFaild:(NSMutableDictionary *)dic { [self downLoadFinishOrStop]; } - (void)remoteQueFinished { [TPUserDefault instance].offlineStatusList = self.dataList; [self downLoadFinishOrStop]; } -(void)checkIfAllCellUnselected { //检查是否出现全部未选中情况 if (beginToDownload) { return; } __block BOOL isAllunSelected = YES; [self.dataList enumerateObjectsUsingBlock:^(NSDictionary* obj, NSUInteger idx, BOOL *stop) { if ([obj[@"isSelected"] intValue] == 1) { isAllunSelected = NO; *stop = YES; } }]; if (isAllunSelected) { self.downloadBtn.enabled = NO; self.clearCacheBtn.enabled = NO; }else { self.downloadBtn.enabled = YES; self.clearCacheBtn.enabled = YES; } } -(void)checkIfNoOfflineData { //检查是否没有更新的离线数据 __block BOOL isAllSelectNoMore = YES; [self.dataList enumerateObjectsUsingBlock:^(NSDictionary* obj, NSUInteger idx, BOOL *stop) { if ([obj[@"isSelected"] intValue] == 1) { if (obj[@"noOfflineData"] && [obj[@"noOfflineData"] intValue] == 0) { isAllSelectNoMore = NO; *stop = YES; } } }]; if (isAllSelectNoMore) { ShowTextMessage(@"所选频道暂时没有新的离线数据"); [self.clearCacheBtn setEnabled:YES]; [self.downloadBtn setTitle:@"开始下载" forState:UIControlStateNormal]; [self.downloadBtn removeTarget:self action:@selector(pauseDownLoad:) forControlEvents:UIControlEventTouchUpInside]; [self.downloadBtn addTarget:self action:@selector(downLoad:) forControlEvents:UIControlEventTouchUpInside]; beginToDownload = NO; self.dataSourceList = [NSMutableArray arrayWithArray:self.dataList]; } } #pragma mark - remoteDelegate //- (void)queDidFinish { // [self downLoadFinishOrStop]; //} - (void)dealloc { [TPUserDefault instance].offlineStatusList = [NSMutableArray arrayWithArray:self.dataList]; [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)needrefreshNightMode:(NSNotification*)noti { self.view.backgroundColor = [UIColor colorWithHexString:CELLBACKCOLOR]; self.offlineDownloadTableView.backgroundColor = [UIColor colorWithHexString:CELLBACKCOLOR]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end