热更新demo

offlineDownLoadCell.m 17KB

    // // offlineDownLoadCell.m // ThePaperDemo // // Created by scar1900 on 14/11/27. // Copyright (c) 2014年 scar1900. All rights reserved. // #import "offlineDownLoadCell.h" #import "ASProgressPopUpView.h" #import "CoreAnimationEffect.h" @interface offlineDownLoadCell()<RemoteDelegate> { float totalSize; NSString *fileName; NSTimer *progressTimer; NSString *creatData; } @property(nonatomic, strong)UILabel *titleLabel; @property(nonatomic, strong)UILabel *dateLabel; @property(nonatomic, strong)UIView *lineView; @property(nonatomic, strong)UIButton *selectBtn; @property(nonatomic, strong)ASProgressPopUpView *progressView; @property(nonatomic, strong)UILabel *downLoadNumLabel; @property(nonatomic, strong)UIButton *clickBtn; @end @implementation offlineDownLoadCell @synthesize dataDic = _dataDic; @synthesize isBeginToDownload = _isBeginToDownload; @synthesize delegate; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor colorWithHexString:BackGroundColor]; // self.selectionStyle = UITableViewCellSelectionStyleNone; totalSize = 0; fileName = @""; [self.progressView showPopUpViewAnimated:YES]; self.clipsToBounds = YES; [self addSubview:self.clickBtn]; [self addSubview:self.titleLabel]; [self addSubview:self.lineView]; [self addSubview:self.dateLabel]; [self addSubview:self.selectBtn]; [self addSubview:self.progressView]; [self addSubview:self.downLoadNumLabel]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needrefreshNightMode:) name:REFRESHAFTERNIGHTMODE object:nil]; } return self; } - (UIButton*)clickBtn { if (!_clickBtn) { _clickBtn = [UIButton buttonWithType:UIButtonTypeCustom]; _clickBtn.backgroundColor = [UIColor clearColor]; [_clickBtn addTarget:self action:@selector(clickHander:) forControlEvents:UIControlEventTouchUpInside]; [_clickBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:CELLBACKCOLOR]) forState:UIControlStateHighlighted]; } return _clickBtn; } - (void)clickHander:(UIButton*)btn { if ([self.delegate respondsToSelector:@selector(clickCell:)]) { [self.delegate clickCell:self.dataDic]; } } - (void)setDataDic:(NSMutableDictionary *)dic { _dataDic = dic; self.titleLabel.text = dic[@"name"]?dic[@"name"]:@""; NSString *updateStr = dic[@"updateDate"]; self.dateLabel.text = updateStr?updateStr:@""; NSString *isSelectStr = dic[@"isSelected"]; if ([isSelectStr intValue] == 1) { self.selectBtn.selected = YES; }else self.selectBtn.selected = NO; // float progressFloat = [dic[@"progressCompletion"] floatValue]; // self.progressView.progress = progressFloat; self.progressView.popUpViewColor = [UIColor colorWithHexString:dic[@"color"]]; self.progressView.progressTintColor = self.progressView.popUpViewColor; // self.progressView.trackImage = imageWithUIColor([UIColor colorWithHexString:LINECOLOR]); // self.progressView.progressImage = imageWithUIColor(self.progressView.popUpViewColor); } - (UILabel*)downLoadNumLabel { if (!_downLoadNumLabel) { _downLoadNumLabel = [UILabel new]; _downLoadNumLabel.textAlignment = NSTextAlignmentLeft; _downLoadNumLabel.textColor = [UIColor colorWithHexString:TextLightGray]; _downLoadNumLabel.font = appFont(TEXT_SIX_LEVELSIZE, NO); _downLoadNumLabel.backgroundColor = [UIColor clearColor]; } return _downLoadNumLabel; } - (void)setIsBeginToDownload:(BOOL)isBegin { _isBeginToDownload = isBegin; if (isBegin) { if (self.selectBtn.selected) { NSDictionary *dic = @{@"n":self.dataDic[@"nodeId"]}; [Remote doJsonAction:0 requestUrl:downLoadOffLineURL parameter:dic delegate:self]; }else { self.dateLabel.hidden = NO; self.selectBtn.hidden = YES; self.progressView.hidden = YES; self.downLoadNumLabel.hidden = YES; } }else { [self hideDownloadStatus]; } } - (UILabel *)titleLabel { if (!_titleLabel) { _titleLabel = [[UILabel alloc]initWithFrame:CGRectZero]; _titleLabel.textColor = [UIColor colorWithHexString:TextBlack]; _titleLabel.backgroundColor = [UIColor clearColor]; } _titleLabel.font = appFont(33.2/2, NO); return _titleLabel; } - (UILabel*)dateLabel { if (!_dateLabel) { _dateLabel = [[UILabel alloc]initWithFrame:CGRectZero]; _dateLabel.textColor = [UIColor colorWithHexString:LINECOLOR]; _dateLabel.textAlignment = NSTextAlignmentLeft; _dateLabel.backgroundColor = [UIColor clearColor]; _dateLabel.hidden = NO; } _dateLabel.font = appFont(9, NO); return _dateLabel; } - (UIButton*)selectBtn { if (!_selectBtn) { _selectBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_selectBtn setImage:Image(@"setting/offlineDownload.png") forState:UIControlStateNormal]; [_selectBtn setImage:Image(@"setting/offlineDownload_s.png") forState:UIControlStateSelected]; [_selectBtn addTarget:self action:@selector(selectToDownload:) forControlEvents:UIControlEventTouchUpInside]; } return _selectBtn; } - (UIView*)lineView { if (!_lineView) { _lineView = [[UIView alloc]initWithFrame:CGRectZero]; _lineView.backgroundColor = [UIColor colorWithHexString:LINECOLOR]; } return _lineView; } - (ASProgressPopUpView*)progressView { if (!_progressView) { _progressView = [[ASProgressPopUpView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault]; _progressView.frame = CGRectZero; _progressView.backgroundColor = [UIColor clearColor]; _progressView.hidden = YES; } _progressView.font = appFont(9, NO); return _progressView; } - (void)selectToDownload:(UIButton*)btn { btn.selected = !btn.selected; if (btn.selected) { [self.dataDic setValue:@"1" forKey:@"isSelected"]; }else { [self.dataDic setValue:@"0" forKey:@"isSelected"]; } if ([self.delegate respondsToSelector:@selector(updateDataList:)]) { [self.delegate updateDataList:self.dataDic]; } } - (void)layoutSubviews { self.titleLabel.frame = CGRectMake(10, CGRectGetHeight(self.bounds)/2-10, 35, 20); self.lineView.frame = CGRectMake(10, CGRectGetHeight(self.bounds)-0.5, CGRectGetWidth(self.bounds)-10, 0.5); self.dateLabel.frame = CGRectMake(10, CGRectGetHeight(self.bounds)-15, CGRectGetWidth(self.bounds)/2-10, 15); self.selectBtn.frame = CGRectMake(CGRectGetWidth(self.bounds)-50, 0, 50, CGRectGetHeight(self.bounds)); self.progressView.frame = CGRectMake(10, CGRectGetHeight(self.bounds)-1, CGRectGetWidth(self.bounds)-10, 1); [self.downLoadNumLabel remakeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.titleLabel.right).offset(20); make.bottom.equalTo(self.titleLabel.bottom); make.width.equalTo(@110); make.height.equalTo(015); }]; [self.clickBtn makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.left); make.top.equalTo(self.top); make.bottom.equalTo(self.bottom); make.right.equalTo(self.right); }]; [super layoutSubviews]; } - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated { if (highlighted) { self.backgroundColor = [UIColor colorWithHexString:CELLBACKCOLOR]; }else { self.backgroundColor = [UIColor colorWithHexString:BackGroundColor]; } } - (void)showDownloadStatus { self.dateLabel.hidden = YES; self.selectBtn.hidden = YES; self.progressView.hidden = NO; self.downLoadNumLabel.hidden = NO; [self beginProgressTimer]; } - (void)hideDownloadStatus { self.dateLabel.hidden = NO; self.selectBtn.hidden = NO; self.progressView.hidden = YES; self.downLoadNumLabel.hidden = YES; } #pragma mark - remoteDelegate - (void)beginProgressTimer { [progressTimer invalidate]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ NSArray *tmpArray = [NSArray arrayWithArray:[TPUserDefault instance].offlineStatusList]; __block float currentByte = 0; [tmpArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if ([obj[@"nodeId"] intValue] == [self.dataDic[@"nodeId"] intValue]) { currentByte = [obj[@"currentByte"] floatValue]; } }]; float percentage = currentByte/totalSize; dispatch_async(dispatch_get_main_queue(), ^{ [self.progressView setProgress:percentage animated:YES]; if (currentByte >= totalSize) { return; } progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(beginProgressTimer) userInfo:nil repeats:NO]; [[NSRunLoop currentRunLoop] addTimer:progressTimer forMode:NSRunLoopCommonModes]; }); }); } - (void)stopProgressTimer { [progressTimer invalidate]; } - (void)startWaitCursor:(int)actionTag { } - (void)stopWaitCursor:(int)actionTag { } - (void)remoteResponsSuccess:(int)actionTag withResponsData:(id)responsData { if (actionTag == 0) { NSString *url = responsData[@"zip"]; fileName = fileNameFromUrl(url); totalSize = [responsData[@"size"] floatValue]; self.downLoadNumLabel.text = [NSString stringWithFormat:@"正在下载%@条文章",responsData[@"recordTotal"]]; if (!self.dataDic[@"updateDate"] || ![self.dataDic[@"updateDate"] isEqualToString:responsData[@"createTime"]]) { [self.dataDic setValue:@"" forKey:@"updateDate"]; [self.dataDic setValue:@"0" forKey:@"noOfflineData"]; self.dateLabel.text = @""; if ([self.delegate respondsToSelector:@selector(simpleUpdateDataList:)]) { [self.delegate simpleUpdateDataList:self.dataDic]; } creatData = responsData[@"createTime"]; [self.dataDic setValue:@"0" forKey:@"noOfflineData"]; if ([self.delegate respondsToSelector:@selector(noOfflineDataInRemote:)]) { [self.delegate noOfflineDataInRemote:self.dataDic]; } [self showDownloadStatus]; if (isIOS7) { [Remote downloadOfflineFileAsyncURLSession:url actionTag:[self.dataDic[@"nodeId"] intValue] parameter:nil fileName:fileName delegate:self]; }else { [Remote downloadOfflineFileAsyncASI:url actionTag:[self.dataDic[@"nodeId"] intValue] parameter:nil fileName:fileName delegate:self]; } }else if (ExistAtPath(ConfigPath(fileName))) { TPLOG(@"已存在%@离线缓存!",self.dataDic[@"name"]); [self.dataDic setValue:@"1" forKey:@"isFinish"]; [[Remote instance].sessionTaskList enumerateObjectsUsingBlock:^(NSMutableDictionary* obj, NSUInteger idx, BOOL *stop) { if ([obj[@"actionTag"] intValue] == [self.dataDic[@"nodeId"] intValue]) { [obj setValue:@"1" forKey:@"finish"]; } }]; [self hideDownloadStatus]; [self.dataDic setValue:@"1" forKey:@"noOfflineData"]; if ([self.delegate respondsToSelector:@selector(noOfflineDataInRemote:)]) { [self.delegate noOfflineDataInRemote:self.dataDic]; } }else { [self.dataDic setValue:@"" forKey:@"updateDate"]; [self.dataDic setValue:@"0" forKey:@"noOfflineData"]; self.dateLabel.text = @""; if ([self.delegate respondsToSelector:@selector(updateDataList:)]) { [self.delegate simpleUpdateDataList:self.dataDic]; } creatData = responsData[@"createTime"]; [self.dataDic setValue:@"0" forKey:@"noOfflineData"]; if ([self.delegate respondsToSelector:@selector(noOfflineDataInRemote:)]) { [self.delegate noOfflineDataInRemote:self.dataDic]; } [self showDownloadStatus]; if (isIOS7) { [Remote downloadOfflineFileAsyncURLSession:url actionTag:[self.dataDic[@"nodeId"] intValue] parameter:nil fileName:fileName delegate:self]; }else { [Remote downloadOfflineFileAsyncASI:url actionTag:[self.dataDic[@"nodeId"] intValue] parameter:nil fileName:fileName delegate:self]; } } }else { __block NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataDic]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [dic setValue:fileName forKey:@"fileName"]; ZipArchive *zipArch = [ZipArchive new]; dispatch_async(dispatch_get_main_queue(), ^{ self.downLoadNumLabel.hidden = NO; self.downLoadNumLabel.text = @"正在解压"; }); if ([zipArch UnzipOpenFile:ConfigPath(fileName)]) { NSString *path = [fileName stringByReplacingOccurrencesOfString:@".zip" withString:@""]; BOOL unzipSuccess = [zipArch UnzipFileTo:ConfigPath(path) overWrite:YES]; if (!unzipSuccess) { [zipArch UnzipCloseFile]; }else { NSString *contentListPath = [NSString stringWithFormat:@"%@/%@.txt",ConfigPath(path),dic[@"nodeId"]]; TPLOG(@"===========%@============",contentListPath); if (ExistAtPath(contentListPath)) { [dic setValue:ConfigPath(path) forKey:@"path"]; [dic setValue:@"1" forKey:@"isFinish"]; NSString *resourceString = [NSString stringWithContentsOfFile:contentListPath encoding:NSUTF8StringEncoding error:nil]; NSString* responseString = [self dealResponseStringBeforeChange:resourceString]; NSData *preJsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *resDic = [self toArrayOrNSDictionary:preJsonData]; [dic setValue:resDic forKey:@"resData"]; [dic setValue:creatData forKey:@"updateDate"]; } } } dispatch_async(dispatch_get_main_queue(), ^{ if ([self.delegate respondsToSelector:@selector(simpleUpdateDataList:)]) { [self.delegate simpleUpdateDataList:dic]; } [self stopProgressTimer]; self.dataDic = [NSMutableDictionary dictionaryWithDictionary:dic]; self.isBeginToDownload = NO; [self.progressView setProgress:0 animated:NO]; }); }); } } - (void)remoteResponsFailed:(int)actionTag withMessage:(NSString *)message resultCode:(NSString *)code{ if (actionTag == 0) { ShowTextMessage(message); [self hideDownloadStatus]; if ([self.delegate respondsToSelector:@selector(checkDownloadUrlFaild:)]) { [self.delegate checkDownloadUrlFaild:self.dataDic]; } }else { [self stopProgressTimer]; ShowTextMessage(message); } } - (id)toArrayOrNSDictionary:(NSData *)jsonData{ NSError *error = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error]; if (jsonObject != nil && error == nil){ return jsonObject; }else{ // 解析错误 return nil; } } //json容错处理 - (NSString*)dealResponseStringBeforeChange:(NSString*)responseString { responseString = [responseString stringByReplacingOccurrencesOfString:@"\\'" withString:@"'"]; return responseString; } - (void)dealloc { [[NSNotificationCenter defaultCenter]removeObserver:self]; [progressTimer invalidate]; } - (void)needrefreshNightMode:(NSNotification*)noti { self.backgroundColor = [UIColor colorWithHexString:BackGroundColor]; self.downLoadNumLabel.textColor = [UIColor colorWithHexString:TextLightGray]; self.titleLabel.textColor = [UIColor colorWithHexString:TextBlack]; self.dateLabel.textColor = [UIColor colorWithHexString:LINECOLOR]; self.lineView.backgroundColor = [UIColor colorWithHexString:LINECOLOR]; [self.clickBtn setBackgroundImage:imageWithUIColor([UIColor colorWithHexString:CELLBACKCOLOR]) forState:UIControlStateHighlighted]; } @end