iOS 学习 - 22 异步解析 JSON,使用 FMDB 存储,TableView 显示

时间:2022-06-03 16:23:10

前提是已经知道了有哪些 key 值

Model 类:

.h

@interface ListModel : NSObject

@property (nonatomic, copy)NSString *time;
@property (nonatomic, copy)NSString *cname;
@property (nonatomic, copy)NSString *summary;
@property (nonatomic, copy)NSString *title;
@property (nonatomic, copy)NSString *type; - (void)createArray:(NSDictionary *)result
dataSource:(NSMutableArray *)dataSource;

.m

- (void)createArray:(NSDictionary *)result
dataSource:(NSMutableArray *)dataSource
{
UserModel *userModel = [[UserModel alloc]init];
NSArray *array = result[@"news"];
for (NSDictionary *dict in array) {
ListModel *listModel = [[ListModel alloc]init];
listModel.cname = [NSString stringWithFormat:@"%@",dict[@"cname"]];
listModel.summary = [NSString stringWithFormat:@"%@",dict[@"summary"]];
listModel.title = [NSString stringWithFormat:@"%@",dict[@"title"]];
listModel.type = [NSString stringWithFormat:@"%@",dict[@"type"]];
listModel.time = [NSString stringWithFormat:@"%@",dict[@"lastUpdateTime"]];
[dataSource addObject:listModel];
//NSLog(@"cname:%@",listModel.type); //时间戳转换为时间
NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:[listModel.time integerValue]];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yy-MM-dd"];
NSString *beginStr = [formatter stringFromDate:startDate];
listModel.time = beginStr;
if (!([userModel selectTable].count > )) {
[userModel insert:listModel];
}
}
}

FMDB:

- (BOOL)delteSqlite {
if ([self isSqliteExist]) {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error;
[manager removeItemAtPath:path error:&error];
if (error) {
NSLog(@"delete sqlite failed");
}else{
NSLog(@"delete sqlite success");
}
return YES;
}else{
NSLog(@"sqlite isn't exist");
return NO;
}
return NO;
} #pragma mark - 检测本地文件是否存在
- (BOOL)isSqliteExist {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:path]) {
NSLog(@"sqlite is exist");
return YES;
}else{
NSLog(@"sqlite isn't exist, prepare to create");
return NO;
}
} #pragma mark -- 建数据库
- (void)openDB {
NSString *path = [NSTemporaryDirectory()stringByAppendingString:@"user.db"];
NSLog(@"path:%@",path);
_db = [FMDatabase databaseWithPath:path];
if ([_db open]) {
//建表
BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS NewsInfo(id integer PRIMARY KEY AUTOINCREMENT,cname text NOT NULL,summary text NOT NULL,title text NOT NULL,type text NOT NULL,time text NOT NULL)"];
if (result) {
NSLog(@"create table success");
}else{
NSLog(@"create tabble success");
[_db close];
}
}else{
[_db close];
NSLog(@"open db failed");
}
} #pragma mark - 查询数据库
- (NSMutableArray *)selectTable
{
if (![_db open]) {
[self openDB];
}
NSMutableArray *tempArray = [NSMutableArray array];
if ([_db open]) {
FMResultSet *resultSet = [_db executeQuery:@"select *from NewsInfo;"];
while ([resultSet next]) {
ListModel *listModel = [[ListModel alloc]init];
listModel.cname = [resultSet objectForColumnName:@"cname"];
listModel.summary = [resultSet objectForColumnName:@"summary"];
listModel.title = [resultSet objectForColumnName:@"title"];
listModel.type = [resultSet objectForColumnName:@"type"];
listModel.time = [resultSet objectForColumnName:@"time"];
[tempArray addObject:listModel];
}
[_db close];
}
return tempArray;
} #pragma mark - 插入进表
- (void)insert:(ListModel *)model
{
if (![_db open]) {
[self openDB];
}
[_db executeUpdate:@"INSERT INTO NewsInfo(cname,summary,title,type,time)VALUES(?,?,?,?,?)",model.cname,model.summary,model.title,model.type,model.time];
} #pragma mark - 修改某个值
- (void)update:(NSString *)value to:(NSString *)key {
if (![_db open]) {
[self openDB];
}
if ([_db open]) {
NSString *updateSql = [NSString stringWithFormat:@"update NewsInfo set %@='%@'",key,value];
BOOL res = [_db executeUpdate:updateSql]; if (!res) {
NSLog(@"error when insert db table");
} else {
NSLog(@"success to insert db table");
}
[_db close];
}
}

VC:

- (void)viewDidLoad {
[super viewDidLoad];
[self addBtn]; self.title = @"新闻";
_userModel = [[UserModel alloc]init];
_dataSource = [[NSMutableArray alloc]initWithCapacity:];
[self.view addSubview:self.tableView]; [self isRequestData];
} #pragma mark - 添加一个删除数据库的按钮
- (void)addBtn {
UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"delete" style:UIBarButtonItemStylePlain target:self action:@selector(deleteSqlite)];
self.navigationItem.rightBarButtonItem = item;
} #pragma mark 删除数据库按钮方法
- (void)deleteSqlite {
[_userModel delteSqlite];
} #pragma mark - 本地数据库有值就不请求数据,取本地数据库值
- (void)isRequestData {
if ([_userModel isSqliteExist]) {
_dataSource = [_userModel selectTable];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}else{
//创建一个异步队列解析 json,防止阻塞主线程
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, );
dispatch_async(queue, ^{
[self urlStr];
});
}
} #pragma mark -- 解析 JSON
- (void)urlStr
{
NSURL *url = [NSURL URLWithString:URLSTR];
NSURLSession *session = [NSURLSession sharedSession];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSError *error1;
//解析 json,返回字典,这里解析出来是 unicode 编码,不影响正常显示
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error1]; ListModel *listModel = [[ListModel alloc]init];
[listModel createArray:dict dataSource:_dataSource]; //数据源开始是空的,因为网络等原因...等数据源有值了,在主线程刷新 TabelView
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}];
[task resume];
} #pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataSource.count;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cell_id = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell_id];
}
ListModel *listModel = _dataSource[indexPath.row];
cell.textLabel.text = listModel.title;
cell.detailTextLabel.text = listModel.time;
return cell;
} #pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ListModel *listModel = _dataSource[indexPath.row];
DetailViewController *detailVC = [[DetailViewController alloc]init];
[self.navigationController pushViewController:detailVC animated:YES];
detailVC.titleStr = listModel.cname;
detailVC.contentStr = listModel.summary;
} #pragma mark -- getter
- (UITableView *)tableView {
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:self.view.frame];
_tableView.delegate = self;
_tableView.dataSource = self;
}
return _tableView;
}

完整代码,见 github