#import
#import "ShenlunPaperCacheModel.h"
NS_ASSUME_NONNULL_BEGIN
pod'FMDB'
typedefvoid(^successBlock)(idresponse);
typedefvoid(^faileBlock)(NSError*error);
@interface ShenlunPaperManage : NSObject
+ (ShenlunPaperManage *)shareManger;
- (void)downFileWithData:(ShenlunPaperCacheModel *)model success:(successBlock)success faile:(faileBlock)faile;
- (BOOL)fileExitInDb:(ShenlunPaperCacheModel *)modal;
- (void)openFileWithData:(ShenlunPaperCacheModel *)model;
- (NSArray *)getAllExamPaperCache;
//获取某个
- (NSArray *)getOneExamPaperCache:(ShenlunPaperCacheModel *)modal;
- (NSString *)getFilePathWithData:(ShenlunPaperCacheModel *)modal;
- (void)deleteCacheFile:(ShenlunPaperCacheModel *)model block:(successBlock)result;
@end
#import "ShenlunPaperManage.h"
#import "AFNetworking.h"
#import"FMDB.h"
@interface ShenlunPaperManage ()
@property (nonatomic, strong) NSURLSessionTask *operation;
@property (nonatomic, copy) NSString *filePath;
@property (retain, nonatomic) NSString *DBName;
@property (retain, nonatomic) FMDatabaseQueue *queue;
@end
@implementation ShenlunPaperManage
+ (ShenlunPaperManage *)shareManger {
static ShenlunPaperManage *manger = nil;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
manger = [[ShenlunPaperManagealloc]init];
});
returnmanger;
}
- (instancetype)init {
self= [superinit];
if(self) {
// 存储路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*documentPath = [pathsobjectAtIndex:0];
_filePath= [documentPathstringByAppendingString:@"/shenlunfiles/"];
// 创建指定路径
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOLisDir =NO;
// fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
BOOLexisted = [fileManagerfileExistsAtPath:_filePathisDirectory:&isDir];
if( !(isDir ==YES&& existed ==YES) ) {//如果文件夹不存在
[fileManagercreateDirectoryAtPath:_filePath withIntermediateDirectories:YES attributes:nil error:nil];
}
[self readyDownloadTable];
}
return self;
}
- (void)downFileWithData:(ShenlunPaperCacheModel *)model success:(successBlock)success faile:(faileBlock)faile {
// NSString *currentTime = [self currentTime];
NSString *fileName = [NSString stringWithFormat:@"%@.pdf", model.title]; // currentTime, model.ID
NSString *filePath = [_filePath stringByAppendingPathComponent:fileName];
model.filePath= filePath;
// 创建请求任务
GYWEAKSELF
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//不设置会报-1016或者会有编码问题
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//不设置会报 error 3840
// manager.responseSerializer. = [NSSet setWithObject:@"text/plain"];
// manager.responseSerializer = [NSSet setWithObject:@"text/plain"];
//创建你得请求url、设置请求头
NSString*urlString = [NSStringstringWithFormat:@"%@",model.url];
NSString*method =@"GET";
NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:method URLString:urlString parameters:nil error:nil];
[requestaddValue:[UtilsgetString:@"token"]forHTTPHeaderField:@"token"];
[requestaddValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//发起请求
NSURLSessionDownloadTask*downloadTask = [managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL*(NSURL*targetPath,NSURLResponse*response) {
//这里设置下载文件的存放地址
return[NSURLfileURLWithPath:model.filePath];
}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error) {
NSLog(@"File downloaded to: %@", filePath);
NSLog(@"File downloaded to: %@", model.filePath);
if(!error) {
if(success) {
success(response);
}
[weakSelfaddDownloadFile:model];
}else{
DebugLog(@"\n===========response===========\n%@:\n%@", model.url, error);
if(faile) {
faile(error);
}
}
}];
[downloadTaskresume];
}
#pragma mark- 打开文件
- (void)openFileWithData:(ShenlunPaperCacheModel *)model {
}
// 将当前时间转为时间戳
- (NSString *)currentTime {
NSDate*currentDate = [NSDatedate];
NSTimeIntervaltimeInterval = [currentDatetimeIntervalSince1970];
NSString*result = [NSStringstringWithFormat:@"%.0f", timeInterval];
returnresult;
}
#pragma mark- 数据库操作
// 初始化数据库,创建数据表
- (void)readyDownloadTable {
_DBName = [self getPath:@"shenlunfiles.db"];
// 打开数据库
_queue = [FMDatabaseQueue databaseQueueWithPath:_DBName];
[_queue inDatabase:^(FMDatabase *db) {
NSString *sql = @"CREATE TABLE IF NOT EXISTS shenlunfiles (id VARCHAR(40),title VARCHAR(100),url VARCHAR(200),filepath VARCHAR(200),filetype VARCHAR(100),PRIMARY KEY (id))";
[dbexecuteUpdate:sql];
}];
}
// 数据库存储路径(内部使用)
- (NSString*)getPath:(NSString*)dbName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString*documentsDirectory = [pathsobjectAtIndex:0];
return[documentsDirectorystringByAppendingPathComponent:dbName];
}
// 写入
- (void)addDownloadFile:(ShenlunPaperCacheModel *)modal {
[_queue inDatabase:^(FMDatabase *db) {
BOOL issuccess = [db executeUpdate:@"REPLACE INTO shenlunfiles(id,title,url,filepath,filetype) VALUES (?,?,?,?,?)", modal.ID, modal.title, modal.url, modal.filePath,modal.fileType];
NSLog(@"下载文件成功,写入数据库:%d", issuccess);
}];
}
// 判断数据库中是否存在(存在,说明下载过了)
- (BOOL)fileExitInDb:(ShenlunPaperCacheModel *)modal {
__blockBOOLexit =NO;
[_queue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select * from shenlunfiles";
sql = [sqlstringByAppendingFormat:@" WHERE id = %@", modal.ID];
FMResultSet*rs =[dbexecuteQuery:sql];
while([rsnext]) {
exit =YES;
}
}];
returnexit;
}
//获取某个真题
- (NSArray *)getOneExamPaperCache:(ShenlunPaperCacheModel *)modal {
NSMutableArray *cachedPapers = [NSMutableArray array];
[_queue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select * from shenlunfiles";
FMResultSet*rs =[dbexecuteQuery:sql];
sql = [sqlstringByAppendingFormat:@" WHERE id = %@", modal.ID];
while([rsnext]) {
NSString* ID = [rsstringForColumn:@"id"];
NSString* title = [rsstringForColumn:@"title"];
NSString* url = [rsstringForColumn:@"url"];
NSString* filePath = [rsstringForColumn:@"filepath"];
NSString*fileType = [rsstringForColumn:@"filetype"];
ShenlunPaperCacheModel *model = [[ShenlunPaperCacheModel alloc]init];
model.ID= ID;
model.title= title;
model.url= url;
model.filePath= filePath;
model.fileType= fileType;
[cachedPapersinsertObject:modelatIndex:0];
}
}];
returncachedPapers;
}
- (NSArray *)getAllExamPaperCache {
NSMutableArray *cachedPapers = [NSMutableArray array];
[_queue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select * from shenlunfiles";
FMResultSet*rs =[dbexecuteQuery:sql];
while([rsnext]) {
NSString* ID = [rsstringForColumn:@"id"];
NSString* title = [rsstringForColumn:@"title"];
NSString* url = [rsstringForColumn:@"url"];
NSString* filePath = [rsstringForColumn:@"filepath"];
NSString*fileType = [rsstringForColumn:@"filetype"];
ShenlunPaperCacheModel *model = [[ShenlunPaperCacheModel alloc]init];
model.ID= ID;
model.title= title;
model.url= url;
model.filePath= filePath;
model.fileType= fileType;
[cachedPapersinsertObject:modelatIndex:0];
}
}];
returncachedPapers;
}
- (NSString *)getFilePathWithData:(ShenlunPaperCacheModel *)modal {
__blockNSString*filePath =nil;
[_queue inDatabase:^(FMDatabase *db) {
NSString *sql = @"select * from shenlunfiles";
sql = [sqlstringByAppendingFormat:@" WHERE id = %@", modal.ID];
FMResultSet*rs =[dbexecuteQuery:sql];
while([rsnext]) {
filePath = [rsstringForColumn:@"filepath"];
}
}];
returnfilePath;
}
- (void)deleteCacheFile:(ShenlunPaperCacheModel *)model block:(successBlock)result {
// 删除数据库
[_queue inDatabase:^(FMDatabase *db) {
NSString *sqlStr = [NSString stringWithFormat:@"DELETE from shenlunfiles WHERE id = %@ ", model.ID];
[dbexecuteUpdate:sqlStr];
}];
// 删除本地文件
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOLblHave = [fileManagerfileExistsAtPath:model.filePath];
if(!blHave) {
NSLog(@"no have");
return;
}else{
NSLog(@" have");
BOOLblDele= [fileManagerremoveItemAtPath:model.filePatherror:nil];
if(blDele) {
NSLog(@"dele success");
}else{
NSLog(@"dele fail");
}
}
if(result) {
result(@{});
}
}
@end
ShenlunPaperCacheModel *model = [[ShenlunPaperCacheModel alloc] init];
model.ID= [NSStringstringWithFormat:@"%@", paper.id];
model.title= paper.title;
model.url= paper.url;
model.fileType=@"shenlunzhentipaper";
if (![[ShenlunPaperManage shareManger] fileExitInDb:model]) {
[weakSelfshowLoading:nil];
[[ShenlunPaperManage shareManger] downFileWithData:model success:^(id response) {
[weakSelfhideLoading];
[weakSelfshowMessage:@"试卷已下载,请至缓存列表查看"];
}faile:^(NSError*error) {
[weakSelfhideLoading];
[weakSelfshowError:@"下载失败"];
}];
}else{
[weakSelfshowMessage:@"您已经下载过了,请至缓存列表查看"];
}
#import
@interface XBCycleProgress : UIView
@property (nonatomic, assign) CGFloat progress;
// 进度条颜色
@property(nonatomic, strong) UIColor *progerssColor;
// 进度条背景颜色
@property(nonatomic, strong) UIColor *progerssBackgroundColor;
// 进度条的宽度
@property(nonatomic, assign) CGFloat progerWidth;
// 进度数据字体大小
@property(nonatomic, assign) CGFloat percentageFontSize;
// 进度数字颜色
@property(nonatomic, strong) UIColor *percentFontColor;
@end
#import "XBCycleProgress.h"
@interface XBCycleProgress ()
@property (nonatomic, weak) UILabel *pLabel;
@end
@implementation XBCycleProgress
- (instancetype)initWithFrame:(CGRect)frame {
if(self= [superinitWithFrame:frame]) {
self.backgroundColor = [UIColor whiteColor];
// 默认颜色
self.progerssBackgroundColor = UIColorFromRGB(0xC1C5D0);
self.progerssColor=UIColorFromRGB(0x02C160);
self.percentFontColor = UIColorFromRGB(0x222222);
// 默认进度条宽度
self.progerWidth=2;
// 默认百分比字体大小
self.percentageFontSize = 6;
// 百分比标签
UILabel *pLabel = [[UILabel alloc] initWithFrame:self.bounds];
pLabel.font = [UIFont boldSystemFontOfSize:self.percentageFontSize];
pLabel.textColor=self.percentFontColor;
pLabel.textAlignment = NSTextAlignmentCenter;
[selfaddSubview:pLabel];
self.pLabel= pLabel;
}
return self;
}
- (void)setProgress:(CGFloat)progress {
_progress= progress;
_pLabel.text = [NSString stringWithFormat:@"%.0f%%", progress];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
// 路径
UIBezierPath *backgroundPath = [[UIBezierPath alloc] init];
// 线宽
backgroundPath.lineWidth=self.progerWidth;
// 颜色
[self.progerssBackgroundColor set];
// 拐角
backgroundPath.lineCapStyle = kCGLineCapRound;
backgroundPath.lineJoinStyle = kCGLineJoinRound;
// 半径
CGFloatradius = (MIN(rect.size.width, rect.size.height) -self.progerWidth) *0.5;
// 画弧(参数:中心、半径、起始角度(3点钟方向为0)、结束角度、是否顺时针)
[backgroundPathaddArcWithCenter:(CGPoint){rect.size.width * 0.5, rect.size.height * 0.5} radius:radius startAngle:M_PI * 1.5 endAngle:M_PI * 1.5 + M_PI * 2 clockwise:YES];
// 连线
[backgroundPathstroke];
// 路径
UIBezierPath *progressPath = [[UIBezierPath alloc] init];
// 线宽
progressPath.lineWidth=self.progerWidth;
// 颜色
[self.progerssColor set];
// 拐角
progressPath.lineCapStyle = kCGLineCapRound;
progressPath.lineJoinStyle = kCGLineJoinRound;
// 画弧(参数:中心、半径、起始角度(3点钟方向为0)、结束角度、是否顺时针)
[progressPathaddArcWithCenter:(CGPoint){rect.size.width*0.5, rect.size.height*0.5}radius:radiusstartAngle:M_PI*1.5endAngle:M_PI*1.5+M_PI*2*_progress/100.0clockwise:YES];
// 连线
[progressPathstroke];
}
@end