数据储存

导第三方
pod ‘AFNetworking’
pod ‘SDWebImage’
pod ‘MBProgressHUD’
pod’FMDB’

AppDelegate.m导航控制器

model

.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface DataModel : NSObject

// 设置一个主键ID
@property(nonatomic , assign)NSInteger classID;

// 图片
@property(nonatomic , strong)NSString *imgsrc;

// 标题
@property(nonatomic , strong)NSString *title;

// 跳转url
@property(nonatomic , strong)NSString *url;

@end

model-------------------
.m
#import “DataModel.h”

@implementation DataModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}

@end
model----------------
sql.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SqliteModel : NSObject

// 单利方法
+(instancetype)initData;
// 初始化数据库
-(void)initSql;
// 初始化表格
-(void)initTable;
// 添加
-(void)addData:(DataModel *)data;
// 删除数据
-(void)deletData:(NSInteger)theid;
// 查询数据
-(NSMutableArray *)inquireArr;
// 关闭数据库
-(void)closeSql;

@end

NS_ASSUME_NONNULL_END

model------------------
sql.m
#import “SqliteModel.h”

// 创建静态变量
static SqliteModel *sql;
static FMDatabase *db;

@implementation SqliteModel

// 初始化单利方法
+(instancetype)initData{

if(!sql){
    
    sql = [[SqliteModel alloc]init];

}

return sql;

}

// 初始化数据库
-(void)initSql{

// 获取Documents目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// 拼接路径
NSString *fileName = [str stringByAppendingString:@"news.db"];
NSLog(@"file:%@",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,所有的数据类型);
[db executeUpdate:@"create table if not exists DataModel(classID integer primary key,imgsrc blob,title text,url text)"];
// 关闭数据库
[db close];

}

// 添加数据
-(void)addData:(DataModel *)data{

if ([db open]) {
    
    //添加数据的sql语句:insert into 表名 values(null,?,?);
    [db executeUpdate:[NSString stringWithFormat:@"insert into DataModel  values(null,'%@','%@','%@')",data.imgsrc,data.title,data.url]];
    NSLog(@"插入成功");

// NSLog(@"---------%@",data);

}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]) {
    //sql 语句格式:select *from 表名
    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.classID = [set intForColumn:@"classID"];
        [arr addObject:model];
       
    }
    
}else{
    NSLog(@"查询失败");
}
[db close];
return arr;

}

-(void)closeSql{

}

@end

view---------------------------
xib
.h拖线
.m
#import “NewsTableViewCell.h”

@implementation NewsTableViewCell

-(void)loadDataModel:(DataModel *)model{

if(model){
    NSLog(@"title====%@",model.title);
    self.titleLabel.text = model.title;
    [self.imgV sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
}

}
xib拖图
controller------------------------
viewcontroller.h没有
viewcontroller.m
#import “ViewController.h”

@interface ViewController ()<UITableViewDelegate , UITableViewDataSource>{
NSMutableArray *dataSource;
}

@property(nonatomic , strong)UITableView *table;

@end

static NSString *oj = @“cell”;

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化
    dataSource = [[NSMutableArray alloc]init];

    self.title = @“数据库”;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];

    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource =self;
    [self.view addSubview:self.table];

    // 注册
    [self.table registerNib:[UINib nibWithNibName:@“NewsTableViewCell” bundle:nil] forCellReuseIdentifier:oj];

    [self loadData];

}

// 显示提示文本
-(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)loadData{

// 显示一个等待指示器
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
hud.removeFromSuperViewOnHide = YES;
[self.view addSubview:hud];
[hud show:YES];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:YULE_PATH parameters:self progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

// NSDictionary *dict = responseObject;
// for (NSDictionary *dic in [dict objectForKey:@“T1348648517839”]) {
// DataModel *mod = [[DataModel alloc]init];
[mod setValuesForKeysWithDictionary:dic];
// // NSLog(@“title===%@”,[dic objectForKey:@“title”]);
// mod.title = [dic objectForKey:@“title”];
// mod.url = [dic objectForKey:@“url”];
// mod.imgsrc = [dic objectForKey:@“imgsrc”];
// [self->dataSource addObject:mod];
// // 隐藏等待指示器
// [hud hide:YES];
for (NSDictionary *dic in responseObject[@“T1348648517839”]) {
DataModel *data =[DataModel new];
[data setValuesForKeysWithDictionary:dic];
[self->dataSource addObject:data];
// 隐藏等待指示器
[hud hide:YES];
}

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"数据请求成功");
        [self showMBHudWithMessage:@"加载成功"];
        [self.table reloadData];
        
    });
 
    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"请求失败");
}];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
// NSLog(@"%@",dataSource);
//
// NSLog(@"%ld",dataSource.count);
return dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];

[cell loadDataModel:dataSource[indexPath.row]];

return cell;

}

-(void)collect{

CollectViewController *collect = [[CollectViewController alloc]init];
[self.navigationController pushViewController:collect animated:YES];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 120;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

NextViewController *next = [[NextViewController alloc]init];
DataModel *data = dataSource[indexPath.row];
next.model = data;
[self.navigationController pushViewController:next animated:YES];

}
@end
nextviewcontroller--------------
nextviewcontroller.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface NextViewController : UIViewController

@property(nonatomic , strong)DataModel *model;

@end

NS_ASSUME_NONNULL_END

nextviewcontroller.m
#import “NextViewController.h”

@interface NextViewController ()

@end

@implementation NextViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];
    //网页视图 ios12摒弃了uiwebview
    WKWebView *webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    //将urlString转换为url
    NSURL *url=[NSURL URLWithString:self.model.url];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //网页视图加载网页
    [webview loadRequest:request];
    //添加到当前视图上
    [self.view addSubview:webview];

}

-(void)collect{

[[SqliteModel initData]initSql];

// NSLog(@"=======%@",self.model);
[[SqliteModel initData]addData:self.model];

}
CollectViewController-----------------
CollectViewController.h没有
CollectViewController.m
#import “CollectViewController.h”

@interface CollectViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic , strong)UITableView *tbv;
@property(nonatomic , strong)NSMutableArray *arr;
@end

@implementation CollectViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @“收藏列表”;

    self.tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tbv.delegate =self;
    self.tbv.dataSource =self;
    [self.view addSubview:self.tbv];
    [self.tbv registerNib:[UINib nibWithNibName:@“NewsTableViewCell” bundle:nil] forCellReuseIdentifier:@“cell”];

}
//视图展示的时候 查询数据库 有没有信息 有展示出来
-(void)viewWillAppear:(BOOL)animated{

[[SqliteModel initData]initSql];
self.arr = [[SqliteModel initData]inquireArr];
for (DataModel *dd in self.arr) {
    NSLog(@"qqqq====%ld",dd.classID);

}
[self.tbv reloadData];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@“cell”];

[cell loadDataModel:self.arr[indexPath.row]];

return cell;

}

// 删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

[[SqliteModel initData]initSql];
NSLog(@"zzzz======%ld",[self.arr[indexPath.row]classID]);
[[SqliteModel initData]deletData:[self.arr[indexPath.row]classID]];
//删除数据
[self.arr removeObject:self.arr[indexPath.row]];

//[self.array removeAllObjects];

[self.tbv reloadData];

// DataModel *mo = self.arr[indexPath.row];
// [[SqliteModel initData]deletData:mo.classID];
// self.arr = [[SqliteModel initData]inquireArr];
// [self.tbv reloadData];

}

//点击跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

[self.tbv deselectRowAtIndexPath:indexPath animated:YES];
CollectNextViewController *collect = [CollectNextViewController new];
DataModel *data = self.arr[indexPath.row];
collect.model = data;
[self.navigationController pushViewController:collect animated:YES];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}

@end
CollectNextViewController-----------------------
CollectNextViewController.h
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface CollectNextViewController : UIViewController

@property(nonatomic , strong)DataModel *model;

@end

NS_ASSUME_NONNULL_END

CollectNextViewController.m
#import “CollectNextViewController.h”

@interface CollectNextViewController ()

@end

@implementation CollectNextViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    //网页视图 ios12摒弃了uiwebview
    WKWebView *webview=[[WKWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    //将urlString转换为url
    NSURL *url=[NSURL URLWithString:self.model.url];
    //创建请求对象
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //网页视图加载网页
    [webview loadRequest:request];
    //添加到当前视图上
    [self.view addSubview:webview];

}

@end
pch----------------------------

$(SRCROOT)
#ifndef PrefixHeader_pch
#define PrefixHeader_pch

#import “DataModel.h”
#import “SqliteModel.h”
#import “NewsTableViewCell.h”
#import “CollectViewController.h”
#import “CollectNextViewController.h”
#import “ViewController.h”
#import “NextViewController.h”
#import <UIImageView+WebCache.h>
#import “AFNetworking.h”
//#import “UIKit+AFNetworking.h”
#import <WebKit/WebKit.h>
#import “FMDatabase.h”
#import “MBProgressHUD.h”
#import “SqliteModel.h”

#define YULE_PATH @“http://c.m.163.com/nc/article/list/T1348648517839/0-20.html
#define YULE_KEY @“T1348648517839”

#endif /* PrefixHeader_pch */

开网-------------

post-------------------------

  • (void)loadData{
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer=[AFJSONResponseSerializer serializer];
    [manager POST:@“http://v.juhe.cn/toutiao/index?key=67968aeebf1f4e3b6170f7217b6f3cdb” parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {

      NSDictionary *json = responseObject;
      
      
      for (NSDictionary *dict in json[@"result"][@"data"]) {
          Model *MT=[Model new];
          [MT setValuesForKeysWithDictionary:dict];
          [self.array addObject:MT];
          
      }
      //刷新表格
      [self.ojtable reloadData];
    

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];

}

post-----------------------------
// 解析数据
-(void)loadData{

// 显示等待指示器
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
hud.removeFromSuperViewOnHide = YES;
[self.view addSubview:hud];
[hud show:YES];


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:@"http://v.juhe.cn/wzpoints/query?lat=40.041478&lon=116.300267&key=6d96ee265cc090b418ee51257ff9c48f" parameters:self headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSDictionary *dict = responseObject;
    self.datasource = [DataModel mj_objectArrayWithKeyValuesArray:dict[@"result"][@"list"]];
    NSLog(@"数据请求成功");
    NSLog(@"datasource ================= %@",self.datasource);
    // 隐藏等待指示器
    [hud hide:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showMBHudWithMessage:@"加载成功"];
        [self.table reloadData];
    });

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"数据请求失败");
}];

}

食材大全-------------------------------
pod ‘FMDB’
pod ‘AFNetworking’
pod ‘MJExtension’
model--------------------------
MenuModel.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface MenuModel : NSObject

@property(nonatomic , strong)NSString *title;

@property(nonatomic , strong)NSString *tags;

// 创建一个主键ID
@property(nonatomic , assign)NSInteger MenuID;

@end

NS_ASSUME_NONNULL_END

MenuModel.m
#import “MenuModel.h”

@implementation MenuModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
@end

SqliteModel--------------------------
SqliteModel.h
#import <Foundation/Foundation.h>
#import “MenuModel.h”
NS_ASSUME_NONNULL_BEGIN

@interface SqliteModel : NSObject

// 单利方法
+(instancetype)initData;
// 创建数据库
-(void)initSql;
// 创建表格
-(void)initTable;
// 添加数据
-(void)addData:(MenuModel *)data;
// 删除数据
-(void)deletData:(NSInteger)theid;
// 查询数据
-(NSMutableArray *)inquireArr;
// 关闭数据库
-(void)closeSql;

@end

NS_ASSUME_NONNULL_END

SqliteModel.m
#import “SqliteModel.h”
#import “FMDatabase.h”

// 创建静态变量
static SqliteModel *sql;
static FMDatabase *db;

@implementation SqliteModel

// 初始化单利方法
+(instancetype)initData{

if (!sql) {
    
    sql = [[SqliteModel alloc]init];
    
}

return sql;

}

// 初始化数据库
-(void)initSql{

// 获取Documents文件目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
// 拼接文件
NSString *fileName = [str stringByAppendingString:@"menu.db"];
NSLog(@"fileName=======%@",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,所有的数据类型);
    [db executeUpdate:@"create table if not exists MenuModel(MenuID integer primary key,title text,tags text)"];
    // 关闭数据库
    [db close];

}
// 添加数据
-(void)addData:(MenuModel *)data{

if ([db open]) {
    
    //添加数据的sql语句:insert into 表名 values(null,?,?);
    [db executeUpdate:[NSString stringWithFormat:@"insert into MenuModel values(null,'%@','%@')",data.title,data.tags]];
    NSLog(@"插入的数据========%@",data);
    NSLog(@"插入成功");
}else{
    
    NSLog(@"插入失败");
    
}
// 关闭数据库
[db close];

}

// 删除数据
-(void)deletData:(NSInteger)theid{

if ([db open]) {
    
    //sql 语句: delete from 表名 where 表名的主键id = ?
    [db executeUpdate:[NSString stringWithFormat:@"delete from MenuModel where MenuID=%ld",theid]];
    NSLog(@"删除成功");
    
}else{
    
    NSLog(@"删除失败");
    
}
// 关闭数据库
[db close];

}

// 查询数据库
-(NSMutableArray *)inquireArr{

// 创建数据
NSMutableArray *arr = [[NSMutableArray alloc]init];
// 创建集合
FMResultSet *set = [[FMResultSet alloc]init];

if ([db open]) {
    
    //sql 语句格式:select *from 表名
    set = [db executeQuery:@"select *from MenuModel"];
    
    while ([set next]) {
        
        MenuModel *model = [[MenuModel alloc]init];
        model.title = [set stringForColumn:@"title"];
        model.tags = [set stringForColumn:@"tags"];
        model.MenuID = [set intForColumn:@"MenuID"];
        
        NSLog(@"model ================ %@",model);
        
        [arr addObject:model];
        NSLog(@"查询成功");
    }
    
}else{
    
    NSLog(@"查询失败");
    
}

// 关闭数据库
[db close];

return arr;

}

-(void)closeSql{

}

@end

view---------------------------------
MenuViewController.h没有

MenuViewController.m没有

Controller------------------
ViewController.h
#import <UIKit/UIKit.h>
#import “MenuModel.h”
@interface ViewController : UIViewController

@property(nonatomic , strong)MenuModel *model;

@end

ViewController.m
#import “ViewController.h”
#import “MenuModel.h”
#import “AFNetworking.h”
#import “MJExtension.h”
#import “CollectViewController.h”
#import “SqliteModel.h”
@interface ViewController ()<UITableViewDelegate , UITableViewDataSource>

@property(nonatomic , strong)UITableView *table;

@property(nonatomic , strong)NSMutableArray *dataSource;

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.dataSource = [[NSMutableArray alloc]init];

    self.title = @“菜谱大全”;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏列表” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];
    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];

    // 设置加载数据方法
    [self reloadData];

}
// 加载数据
-(void)reloadData{

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:@"http://apis.juhe.cn/cook/query?menu=%E8%A5%BF%E7%BA%A2%E6%9F%BF&rn=10&pn=3&key=f39f197e0fae5489277675172b4cea90" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSDictionary *dict = responseObject;
    self.dataSource = [MenuModel mj_objectArrayWithKeyValuesArray:dict[@"result"][@"data"]];
    NSLog(@"请求成功");
    NSLog(@"datasource ================= %@",self.dataSource);
    [self.table 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";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];
if (cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}

MenuModel *mod = self.dataSource[indexPath.row];

cell.textLabel.text = mod.title;
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.detailTextLabel.text = mod.tags;
cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
cell.detailTextLabel.numberOfLines = 0;

return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

[self.table deselectRowAtIndexPath:indexPath animated:YES];

MenuModel *mod = self.dataSource[indexPath.row];

[[SqliteModel initData]initSql];

[[SqliteModel initData]addData:mod];

}
-(void)collect{

CollectViewController *collect = [[CollectViewController alloc]init];
[self.navigationController pushViewController:collect animated:YES];

}
@end
CollectViewController----------------------
CollectViewController.h没有
CollectViewController.m

#import “CollectViewController.h”
#import “MenuModel.h”
#import “SqliteModel.h”
@interface CollectViewController ()<UITableViewDelegate , UITableViewDataSource>
@property(nonatomic , strong)UITableView *table;

@property(nonatomic , strong)NSMutableArray *dataSource;
@end

@implementation CollectViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.dataSource = [[NSMutableArray alloc]init];

    self.title = @“收藏列表”;
    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];

}
// 视图即将显示的时候
-(void)viewWillAppear:(BOOL)animated{

[[SqliteModel initData]initSql];
self.dataSource = [[SqliteModel initData]inquireArr];
[self.table reloadData];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *oj = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];
if (cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}

MenuModel *mod = self.dataSource[indexPath.row];

cell.textLabel.text = mod.title;
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.detailTextLabel.text = mod.tags;
cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
cell.detailTextLabel.numberOfLines = 0;

return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

[[SqliteModel initData]initSql];

[[SqliteModel initData]deletData:[self.dataSource[indexPath.row]MenuID]];

// 删除数据
[self.dataSource removeObject:self.dataSource[indexPath.row]];

// 刷新表格
[self.table reloadData];

}

@end

地图-----------------------------
导三方
pod ‘FMDB’
pod ‘AFNetworking’
pod ‘MJExtension’
pod ‘MBProgressHUD’

pch

#ifndef PrefixHeader_pch
#define PrefixHeader_pch

#import “DataModel.h”
#import “SqliteModel.h”
#import “NewsTableViewCell.h”
#import “ViewController.h”
#import “NextViewController.h”
#import “CollectViewController.h”
#import “AFNetworking.h”
#import “FMDatabase.h”
#import “MJExtension.h”
#import “MBProgressHUD.h”

#endif /* PrefixHeader_pch */

frameworks
导两个包
mapkit
corelocation

model----------------
DataModel.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface DataModel : NSObject

// 设置一个主键ID
@property(nonatomic , assign)NSInteger classID;

// 设置标题
@property(nonatomic , strong)NSString *title;

// 设置详情
@property(nonatomic , strong)NSString *detail;

@end

NS_ASSUME_NONNULL_END

DataModel.m
#import “DataModel.h”

@implementation DataModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
@end

SqliteModel.h
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SqliteModel : NSObject

// 单利方法
+(instancetype)initData;
// 初始化数据库
-(void)initSql;
// 初始化表格
-(void)initTable;
// 添加数据
-(void)addData:(id)data;
// 删除数据
-(void)deletData:(NSInteger)theid;
// 查询数据
-(id)inquireArr;
// 关闭数据库
-(void)closeSql;

@end

NS_ASSUME_NONNULL_END

SqliteModel.m
#import “SqliteModel.h”
#import “DataModel.h”
// 创建静态变量
static SqliteModel *sql;
static FMDatabase *db;

@implementation SqliteModel

// 初始化单利方法

  • (instancetype)initData{

    if (!sql) {

      sql = [[SqliteModel alloc]init];
    

    }

    return sql;

}

// 初始化数据库
-(void)initSql{

// 获取Documents目录
NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
// 拼接路径
NSString *fileName = [str stringByAppendingString:@"str.db"];
// 创建数据库
db = [[FMDatabase alloc]initWithPath:fileName];

if ([db open]) {
    
    NSLog(@"打开数据库成功");
    
    // 初始化表格
    [self initTable];
    
}else{
    
    NSLog(@"打开数据库失败");
    
}

}

// 初始化表格
-(void)initTable{

//初始化数据库表格的格式:create table if not exists 表名(主键id integer primary key,所有的数据类型);
[db executeUpdate:@"create table if not exists DataModel(classID integer primary key,title text,detail text)"];
// 关闭数据库
[db close];

}

// 添加数据
-(void)addData:(DataModel *)data{

if ([db open]) {
    
    //添加数据的sql语句:insert into 表名 values(null,?,?);
    [db executeUpdate:[NSString stringWithFormat:@"insert into DataModel values(null,'%@','%@')",data.title,data.detail]];
    NSLog(@"插入: =============== %@",data);
    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];

}

// 查询数据
-(NSArray *)inquireArr{

// 创建数据
NSMutableArray *arr = [[NSMutableArray alloc]init];
// 创建集合
FMResultSet *set = [[FMResultSet alloc]init];

if ([db open]) {
    
    //sql 语句格式:select *from 表名
    set = [db executeQuery:@"select * from DataModel"];
    
    // 判断有没有东西
    while ([set next]) {
        
        DataModel *model = [[DataModel alloc]init];
        model.classID = [set intForColumn:@"classID"];
        model.title = [set stringForColumn:@"title"];
        model.detail = [set stringForColumn:@"detail"];
        NSLog(@"model ================ %@",model);
        
        [arr addObject:model];
        NSLog(@"查找成功");
    }
}else{
    
    NSLog(@"查询失败");
    
}

// 关闭数据库
[db close];
return arr;

}
-(void)closeSql{

}

@end

view--------------------------
注册xib

ViewController-----------------------
ViewController.h没有
ViewController.m
#import “ViewController.h”
//引入头文件 ‘地图框架’
#import <MapKit/MapKit.h>
//引入头文件 ‘定位框架’
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<MKMapViewDelegate , CLLocationManagerDelegate>
//定义属性 ‘地图视图’
@property(nonatomic,strong)MKMapView *MapView;
//定义属性 ‘地理位置管理者’
@property(nonatomic,strong)CLLocationManager *locManager;
@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @“地图”;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“附近违章高发地” style:UIBarButtonItemStyleDone target:self action:@selector(click)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“定位” style:UIBarButtonItemStyleDone target:self action:@selector(currentBtnDidPress:)];

    //初始化MKMapView ‘地图视图’
    self.MapView = [[MKMapView alloc]initWithFrame:self.view.frame];
    //设置地图的样式 ‘MKMapTypeSatellite卫星地图’ ‘MKMapTypeStandard平面地图’
    self.MapView.mapType = MKMapTypeStandard;
    //签订协议
    self.MapView.delegate = self;
    //添加到视图
    [self.view addSubview:self.MapView];

    //实例化位置管理者对象
    self.locManager = [[CLLocationManager alloc]init];
    //签订协议
    self.locManager.delegate = self;
    //申请用户授权
    [self.locManager requestWhenInUseAuthorization];

}
-(void)click{

NextViewController *next = [[NextViewController alloc]init];
[self.navigationController pushViewController:next animated:YES];

}
//获取当前按钮触发
-(void)currentBtnDidPress:(id)sender{

//开始获取位置信息,调用此方法后,协议中的方法才会执行
[self.locManager startUpdatingLocation];//通过位置管理者开始位置更新

}

//获取当前位置信息后触发的回调方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

//获取当前位置  CLLocation位置   locations位置信息一个数组,获取最后一个最新的位置信息
CLLocation *cation = [locations lastObject];
//获取经纬度    coordinate坐标  ‘经纬度=当前位置的坐标’
CLLocationCoordinate2D locationCoor = cation.coordinate;
//输出一下位置信息   longitude经度   latitude纬度
NSLog(@"位置:经度:%g,纬度:%g",locationCoor.longitude,locationCoor.latitude);

//让地图的显示区缩小   MKCoordinateRegion显示区    传入一个经纬度 和两个需要缩成的大小
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(locationCoor, 180, 180);
//添加到地图视图上  给地图缩小
[self.MapView setRegion:region animated:YES];


//反向地址解析,将经纬度转换为字符串
//初始化地址解析  ‘CLGeocoder地址解析’
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
//解析   reverseGeocodeLocation传入一个位置
[geocoder reverseGeocodeLocation:cation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    
    //获取其中的一个地址信息
    CLPlacemark *place = [placemarks lastObject];
    
    //做一个大头针
    //初始化一个描点
    MKPointAnnotation *point = [[MKPointAnnotation alloc]init];
    //设置大头针的标题   显示当前的位置信息
    point.title = [NSString stringWithFormat:@"我的位置:%@",place.name];
    //设置大头针显示的经纬度  传入locationCoor当前的经纬度
    point.coordinate = locationCoor;
    //添加到地图上   必须是Annotation的类型
    [self.MapView addAnnotation:point];
    
}];

}
//设置锚点视图的回调方法,当地图调用addAnnotation:方法时会触发 点击大头针是触发的方法
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation{
//静态字符串标识
static NSString *iden = @“pin”;
//初始化描点视图
MKPinAnnotationView *pin = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:iden];

//设置掉落状态
pin.animatesDrop = YES;
//设置泡泡效果
pin.canShowCallout = YES;

return pin;

}

@end

NextViewController-------------
NextViewController.h
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface NextViewController : UIViewController
@property(nonatomic , strong)DataModel *model;
@end

NS_ASSUME_NONNULL_END

NextViewController.m
#import “NextViewController.h”
@interface NextViewController ()<UITableViewDelegate , UITableViewDataSource>

@property(nonatomic , strong)UITableView *table;

@property(nonatomic , strong)NSMutableArray *datasource;

@end

@implementation NextViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    // 初始化数组
    self.datasource = [[NSMutableArray alloc]init];

    self.title = @“附近违章高发地”;
    // 设置表格
    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    // 设置dialing
    self.table.delegate = self;
    self.table.dataSource = self;
    // 添加到视图上
    [self.view addSubview:self.table];

    // 添加一个导航右边按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(collect)];

    //加载数据
    [self loadData];

}
// 显示提示文本
-(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)loadData{

// 显示等待指示器
MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.view];
hud.removeFromSuperViewOnHide = YES;
[self.view addSubview:hud];
[hud show:YES];


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:@"http://v.juhe.cn/wzpoints/query?lat=40.041478&lon=116.300267&key=6d96ee265cc090b418ee51257ff9c48f" parameters:nil  progress:nil
    
 success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSDictionary *dict = responseObject;
    self.datasource = [DataModel mj_objectArrayWithKeyValuesArray:dict[@"result"][@"list"]];
    NSLog(@"数据请求成功");
    NSLog(@"datasource ================= %@",self.datasource);
    // 隐藏等待指示器
    [hud hide:YES];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showMBHudWithMessage:@"加载成功"];
        [self.table 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";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];
if (cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}

DataModel *mod = self.datasource[indexPath.row];
cell.textLabel.text = mod.title;
cell.detailTextLabel.text = mod.detail;

return cell;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 80;
}

// 点击单元格进行跳转到收藏界面
-(void)collect{

CollectViewController *collect = [[CollectViewController alloc]init];
[self.navigationController pushViewController:collect animated:YES];

}

// 点击单元格进行收藏
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

DataModel *model = self.datasource[indexPath.row];

[[SqliteModel initData]initSql];

[[SqliteModel initData]addData:model];

}

@end

CollectViewController--------------------
CollectViewController.h没有
CollectViewController.m
#import “CollectViewController.h”

@interface CollectViewController ()<UITableViewDelegate , UITableViewDataSource>

@property(nonatomic , strong)UITableView *table;
@property(nonatomic , strong)NSMutableArray *DataArr;

@end

@implementation CollectViewController
// 视图即将显示
-(void)viewWillAppear:(BOOL)animated{

[[SqliteModel initData]initSql];
self.DataArr = [[SqliteModel initData]inquireArr];
NSLog(@"查找数据: =============== %@",self.DataArr);
[self.table reloadData];

}

  • (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @“收藏列表”;
    self.table = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.DataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *oj = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:oj];
if (cell == nil) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
}
DataModel *mod = self.DataArr[indexPath.row];
cell.textLabel.text = mod.title;
cell.detailTextLabel.text = mod.detail;

return cell;

}

// 点击单元格编辑删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

[[SqliteModel initData]initSql];

// NSLog(@“zzz=======%ld”,[self.DataArr[indexPath.row]classID]);
[[SqliteModel initData]deletData:[self.DataArr[indexPath.row]classID]];
// 删除数据
[self.DataArr removeObject:self.DataArr[indexPath.row]];

// 刷新表格
[self.table reloadData];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 80;
}

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值