首先导入cocopods文件
pod 'AFNetworking'
pod 'FMDB'
pod 'MBProgressHUD'
首先创建两个Controller
我这里创建的是oneViewController(这个是住界面点击收藏之后跳转进去的界面)和twoViewController(这个是点击cell跳转进去的界面)
然后在创建两个Model
我这里创建的是Model和DataModel
然后在创建一个继承于UITableViewCell的TableViewCell
首先ViewController.m里面
#import "ViewController.h"
#import <AFNetworking.h>
#import "TableViewCell.h"
#import "DataModel.h"
#import "twoViewController.h"
#import "oneViewController.h"
#import "Model.h"
#import "MBProgressHUD.h"
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *DataSource;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tab.delegate=self;
self.tab.dataSource=self;
self.navigationItem.title=@"好好学习";
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"收藏界面" style:UIBarButtonItemStyleDone target:self action:@selector(click)];
[self.view addSubview:self.tab];
[self.tab registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
self.DataSource=[[NSMutableArray alloc]init];
[self AFN];
}
// 显示提示文本
-(void)showMBHudWithMessage:(NSString *)msg{
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
// 设置文本的提示样式
hud.mode = MBProgressHUDModeIndeterminate;
// 自动从父视图移除
hud.removeFromSuperViewOnHide = YES;
hud.labelText = msg;
[self.view addSubview:hud];
[hud show:YES];
[hud hide:YES afterDelay:2.0];
}
//-(void)HUD{
// MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
// // 设置文本的提示样式
// hud.mode = MBProgressHUDModeIndeterminate;
// // 自动从父视图移除
// hud.removeFromSuperViewOnHide = YES;
//
// UILabel *msg=[[UILabel alloc]init];
// msg.text=@"正在等待";
// hud.labelText = msg;
// [self.view addSubview:hud];
// [hud show:YES];
// [hud hide:YES afterDelay:2.0];
//
//
//}
-(void)AFN{
// 显示一个等待指示器
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
hud.removeFromSuperViewOnHide = YES;
[self.view addSubview:hud];
[hud show:YES];
AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
manger.responseSerializer=[AFHTTPResponseSerializer serializer];
[manger GET:@"http://c.m.163.com/nc/article/list/T1348648517839/0-20.html" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功");
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:1 error:nil];
NSDictionary *arr=[dic objectForKey:@"T1348648517839"];
for (NSDictionary *dic in arr) {
DataModel *model=[DataModel new];
[model setValuesForKeysWithDictionary:dic];
[self.DataSource addObject:model];
// 隐藏等待指示器
[hud hide:YES];
NSLog(@"%@",self.DataSource);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self showMBHudWithMessage:@"加载成功"];
[self.tab reloadData];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.DataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *oj=@"cell";
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];
if (cell==nil) {
cell=[[TableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}
DataModel *model=self.DataSource[indexPath.row];
self.tab.rowHeight=150;
[cell loadData:model];
// cell.zhu.text=model.title;
//
// cell.fu.text=model.mtime;
//
// cell.img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.imgsrc]]];
//
return cell;
}
-(void)click{
oneViewController *one=[oneViewController new];
[self.navigationController pushViewController:one animated:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
twoViewController *two=[twoViewController new];
two.str =self.DataSource[indexPath.row];
[self.navigationController pushViewController:two animated:YES];
}
@end
然后在oneViewController.h里面
#import <UIKit/UIKit.h>
#import "DataModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface oneViewController : UIViewController
@property(nonatomic,strong)DataModel *mode;
@end
NS_ASSUME_NONNULL_END
然后是oneViewController.m
#import "oneViewController.h"
#import "DataModel.h"
#import "Model.h"
#import "TableViewCell.h"
@interface oneViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *arr;
@end
@implementation oneViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title=@"收藏列表";
self.tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tab.delegate=self;
self.tab.dataSource=self;
[self.tab registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
[self.view addSubview:self.tab];
}
-(void)viewWillAppear:(BOOL)animated{
[[Model initData]initSql];
//把从数据查询到的数据加载到arr
self.arr=[[Model initData]inquireArr];
//
// for (DataModel *dd in self.arr) {
// NSLog(@"qqqq====%ld",dd.classID);
//
// }
//刷新表格
[self.tab reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *oj=@"cell";
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];
[cell loadData:self.arr[indexPath.row]];
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
[[Model initData]initSql];
//首先确认主键ID
[[Model initData]deletData:[self.arr[indexPath.row]classID]];
//确认完主键ID删除数据
[self.arr removeObject:self.arr[indexPath.row]];
[self.tab reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 150;
}
@end
然后在twoViewController.h
#import <UIKit/UIKit.h>
#import "DataModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface twoViewController : UIViewController
@property(nonatomic,strong)DataModel *str;
@end
NS_ASSUME_NONNULL_END
然后是twoViewController.m
#import "twoViewController.h"
#import <WebKit/WebKit.h>
#import "Model.h"
@interface twoViewController ()
@property(nonatomic,strong)WKWebView *webview;
@end
@implementation twoViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"网页视图";
self.webview=[[WKWebView alloc]initWithFrame:self.view.bounds];
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStyleDone target:self action:@selector(click)];
//
[self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.str.url]]]];
[self.view addSubview:self.webview];
}
-(void)click{
[[Model initData]initSql];
[[Model initData]addData:self.str];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
然后在DataModel.h里面
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface DataModel : NSObject
@property(nonatomic,strong)NSString *imgsrc,*title,*mtime,*url;
// 设置一个主键ID
@property(nonatomic , assign)NSInteger classID;
@end
NS_ASSUME_NONNULL_END
然后在DataModel.m里面
#import "DataModel.h"
@implementation DataModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
@end
然后在Model.h里面
#import <Foundation/Foundation.h>
#import "DataModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface Model : NSObject
//单利方法
+(instancetype)initData;
//初始化数据库
-(void)initSql;
//初始化表格
-(void)initTable;
//添加 从解析里面的数据添加到数据库里面 所以是DataModel
-(void)addData:(DataModel *)data;
//删除
-(void)deletData:(NSInteger )theid;
//查询数据
-(NSMutableArray *)inquireArr;
//关闭数据库
-(void)closeSql;
@end
NS_ASSUME_NONNULL_END
然后在Model.m里面写数据持久化
#import "Model.h"
#import "FMDatabase.h"
//创建静态变量
static Model *sql;
static FMDatabase *db;
@implementation Model
//初始化单利方法
+(instancetype)initData{
if (!sql) {
sql=[[Model alloc]init];
}
return sql;
}
//初始化数据库
-(void)initSql{
//获取Documents目录
NSString *str=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//拼接路径
NSString *fileName=[str stringByAppendingString:@"strmb.db"];
NSLog(@"%@",fileName);
//创建数据库
db=[[FMDatabase alloc]initWithPath:fileName];
if ([db open]) {
NSLog(@"打开数据库成功");
//初始化表格
[self initTable];
}else{
NSLog(@"打开数据库失败");
}
}
//初始化表格
-(void)initTable{
//初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型); : 如果不存在DataModel(classID integer primary key,imgsrc blob,title text,url text),则创建表
[db executeUpdate:@"create table if not exists DataModel(classID integer primary key,imgsrc blob,title text,url text,mtime text)"];
//关闭数据库
[db close];
}
//添加数据
-(void)addData:(DataModel *)data{
//添加数据的sql语句:insert into 表名 values(null,?,?);
if ([db open]) {
[db executeUpdate:[NSString stringWithFormat:@"insert into DataModel values(null,'%@','%@','%@','%@')",data.imgsrc,data.title,data.url,data.mtime]];
NSLog(@"插入成功");
}else{
NSLog(@"添加失败");
}
//关闭数据库
[db close];
}
//删除数据
-(void)deletData:(NSInteger)theid{
if ([db open]) {
//sql 语句: delete from 表名 where 表名的主键id = ?
[db executeUpdate:[NSString stringWithFormat:@"delete from DataModel where classID=%ld",theid]];
NSLog(@"删除成功");
}else{
NSLog(@"删除失败");
}
//关闭数据库
[db close];
}
//查询数据库
-(NSMutableArray *)inquireArr{
//创建数据
NSMutableArray *arr=[NSMutableArray new];
//集合
FMResultSet *set=[FMResultSet new];
if ([db open]) {
set=[db executeQuery:@"select *from DataModel"];
//判断有没有东西
while ([set next]) {
DataModel *model=[[DataModel alloc]init];
model.imgsrc=[set stringForColumn:@"imgsrc"];
model.title=[set stringForColumn:@"title"];
model.url=[set stringForColumn:@"url"];
model.mtime = [set stringForColumn:@"mtime"];
model.classID=[set intForColumn:@"classID"];
[arr addObject:model];
}
}else{
NSLog(@"查询失败");
}
[db close];
return arr;
}
@end
然后是我们创建的TableViewCell
.h里面是Xib拖得三个属性
然后倒入头文件
#import "DataModel.h"
我这里定义的三个是
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UILabel *zhu;
@property (weak, nonatomic) IBOutlet UILabel *fu;
然后在里面写一个方法
-(void)loadData:(DataModel *)mod;
然后是TableViewCell.m里面
#import "TableViewCell.h"
@implementation TableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
-(void)loadData:(DataModel *)mod{
if (mod) {
self.zhu.text=mod.title;
self.fu.text=mod.mtime;
self.img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:mod.imgsrc]]];
}
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end