iOS 学习 - 22 异步解析 JSON,使用 FMDB 存储,TableView 显示
前提是已经知道了有哪些 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
iOS 学习 - 22 异步解析 JSON,使用 FMDB 存储,TableView 显示的更多相关文章
- 前端学习之——js解析json数组
** 前端学习之——js解析json数组** 解析json数组即对JSONArray的遍历 一.对于标准的json数组如: var result=[{"flag":1," ...
- iOS学习之数据解析
解析:按照约定好的格式提取数据的过程叫做解析; 后台开发人员按照约定好的格式存入数据,前端开发人员按照约定的格式读取数据; 主流的格式: XML / JSON 前端和后台都能识别的格式; XML解析 ...
- 《项目经验》--后台一般处理程序向前台JS文件传递JSON,JS解析JSON,将数据显示在界面--显示在DropDownList 或 显示在动态创建的table中
http://blog.csdn.net/mazhaojuan/article/details/8599167 先看一下我要实现的功能界面: 这篇文章主要介绍:后台一般处理程序把从数据库查找的数据,转 ...
- iOS网络-02-数据解析(JSON与XML)
数据交互格式 服务器返回给用户的数据,通常是以下两种方式: JSON XML JSON 一种轻量级的数据数据格式,体积比XML小,是服务器返回给移动端通常采用的格式 用使用JSON文件中的数据,需要对 ...
- 【原】iOS学习之XML与JSON两种数据结构比较和各自底层实现
1.XML与JSON两种数据结构的优缺点 1> XML 优点: 格式统一, 符合标准 容易与其他系统进行远程交互, 数据共享比较方便 缺点: XML文件格式文件庞大, 格式复杂, 传输占 ...
- ANDROID_MARS学习笔记_S02_013_Gson解析json串
1.MainActivity.java package com.json; import java.io.IOException; import java.io.StringReader; impor ...
- Python学习--22 异步I/O
在同步IO中,线程启动一个IO操作然后就立即进入等待状态,直到IO操作完成后才醒来继续执行.而异步IO方式中,线程发送一个IO请求到内核,然后继续处理其他的事情,内核完成IO请求后,将会通知线程IO操 ...
- 【原】iOS学习之UIStoryboardSegue解析
在 Storyboard 的可视化编程中,跳转界面就是按住 Ctrl 使用鼠标头一条连线就可以解决,相当的简单!本篇博客主要就是介绍这条连线,在iOS中,这条连线也是一个对象,也有其自己的初始化方法和 ...
- iOS学习22之视图控制器
1.自定义视图 1> 概述 定义视图:系统标准UI之外,自己组合而出的新的视图. 定义视图的优点: iOS提供了很多UI组件,借助它们我们可以实现不同的功能.尽管如此,实际开发中,我们还需要 ...
随机推荐
- android给View设置上下左右边框
给View控件设置边框,可以动态设置上下左右.通过布局文件就能搞定 1.在drawable文件夹下新建一个shape_main_list_bg.xml文件 <layer-list xmlns:a ...
- C#:根据银行卡卡号判断银行名称
原文地址:android 根据银行卡卡号判断银行 原文是 java ,现在将它翻译成 C# ,并对代码重新编排整理,博主是一个今年刚出来的应届毕业生,不足之处请多多包涵. 根据银行卡号判断所属银行,依 ...
- Linux内存管理之bootmem分配器
为什么要使用bootmem分配器,内存管理不是有buddy系统和slab分配器吗?由于在系统初始化的时候需要执行一些内存管理,内存分配的任务,这个时候buddy系统,slab分配器等并没有被初始化好, ...
- 开发中常用js记录(二)
(1)获得asp.net控件的value值 document.getElementById('<%=SUKid.ClientID %>').value (2)获得选中值 $('#selec ...
- jar包依赖性查询
项目中碰到jar包冲突,需要排除一些jar包时先要了解jar的依赖关系,maven提供了命令行来查询: mvn dependency:tree 返回依赖的属性结构
- C# 保护Excel文档
C# 保护Excel文档 说到保护excel文档,我们首先想到的是密码保护的方式,但excel与word有点不一样,一般情况下,每个excel工作薄都或多或少地含有一定数量的工作表,因此保护excel ...
- Oracle手边常用命令及操作语句
Oracle手边常用命令及操作语句 作者:白宁超 时间:2016年3月4日11:24:08 摘要:日常使用oracle数据库过程中,常用脚本命令莫不是用户和密码.表空间.多表联合.执行语句等常规操作. ...
- CSS实现单行与多行文字省略(truncation)
在上一篇文章小div布局之卡片堆叠(card-stacking)中有多行文字溢出省略的效果,这篇文章就对这种效果(包括单行文字溢出省略)的实现做个简单的记录,以防自己忘记.具体来说,就是要实现这种文字 ...
- 【LeetCode】House Robber III(337)
1. Description The thief has found himself a new place for his thievery again. There is only one ent ...
- AssetsManagerEx 组件使用说明
原因 在网络上找了一圈也没有找到一个像样的说明.如果不是我们技术组的大大说这个东西可以用我都快放弃了. 稍微阅读了一下这个组件的源代码.发现该有的功能都有(如下所列). 其实最初吸引我们用这个东西的功 ...