数据库使用

#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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,458评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,030评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,879评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,278评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,296评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,019评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,633评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,541评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,068评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,181评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,318评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,991评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,670评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,183评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,302评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,655评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,327评论 2 358

推荐阅读更多精彩内容