首先把MJExtension 第三方文件拖入到工程里面 Model类和View类里面照常写东西 View里面用xib照常拖
然后在VC.m里面引入#import “AFNetworking/AFNetworking.h”
#import “MJExtension/MJExtension.h”
#import “Model.h” 头文件
主要就是那一行代码
//数组包子店
self.dataSource = [Model mj_objectArrayWithKeyValuesArray:responseObject[@"T1348647853363"]];
/* ================ 字典包数组==============
// [mjmodel mj_setupObjectClassInArray:^NSDictionary *{
// return @"类的数组属性":[字典对应的model class ];
// }];
*/
接下来是解析部分
-(void)createAFN{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@“http://c.m.163.com/nc/article/headline/T1348647853363/0-20.html” parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//数组包子店
self.dataSource = [Model mj_objectArrayWithKeyValuesArray:responseObject[@"T1348647853363"]];
/* ================ 字典包数组==============
// [mjmodel mj_setupObjectClassInArray:^NSDictionary *{
// return @"类的数组属性":[字典对应的model class ];
// }];
*/
[self.tbv reloadData];
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@“Error: %@”, error);
}];
}
其他部分照常写
FMDB
第一 :
1 把FMDB的第三方拖入到工程里面 创建DataModel 继承NSObject ,这个DataModel里面写的是解析的一些数据 在整个FMDB里面 属于表名 在DataModel里面必须定义一个NSInterger 类型的classID 属于主键ID
@interface DataModel : NSObject
@property(nonatomic,strong)NSString *imgsrc,*title,*mtime,*url;
// 设置一个主键ID
@property(nonatomic , assign)NSInteger classID;
@end
下面是DataModel.m里面的方法:
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
第二:在定义一个Model类 继承于NSObject 在Model类里面主要写了FMDB的一些增,删,改,查
首先在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
其次是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继承UITableViewCell 进行拖拽xib约束
其次是拖拽到TableViewCell.h里面
#import <UIKit/UIKit.h>
#import “DataModel.h”
NS_ASSUME_NONNULL_BEGIN
@interface TableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UILabel *zhu;
@property (weak, nonatomic) IBOutlet UILabel *fu;
-(void)loadData:(DataModel *)mode;
然后在TableViewCell.m里面实现方法
-(void)loadData:(DataModel *)mode{
if (mode) {
self.zhu.text=mode.title;
self.fu.text=mode.mtime;
self.img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:mode.imgsrc]]];
}
}
第三:是在VC里面进行解析接口添加到表格里面
#import “ViewController.h”
#import <AFNetworking.h>
#import “TableViewCell.h”
#import “DataModel.h”
#import “oneViewController.h”
#import “twoViewController.h”
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *DATAsource;
@end
@implementation ViewController
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.DATAsource=[[NSMutableArray alloc]init];
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 AFN];
}
-(void)click{
twoViewController *two=[twoViewController new];
[self.navigationController pushViewController:two animated:YES];
}
-(void)AFN{
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];
}
dispatch_async(dispatch_get_main_queue(), ^{
[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{
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@“cell”];
//
//
// if (cell==nil) {
// cell=[[TableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:oj];
// }
DataModel *model=self.DATAsource[indexPath.row];
self.tab.rowHeight=150;
cell.zhu.text=model.title;
cell.fu.text=model.mtime;
cell.img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.imgsrc]]];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
oneViewController *one=[oneViewController new];
one.model= self.DATAsource[indexPath.row];
[self.navigationController pushViewController:one animated:YES];
}
@end
其次创建OneVC
在OneVC.h里面
引入 DataModel.h 进行属性传值
#import <UIKit/UIKit.h>
#import “DataModel.h”
NS_ASSUME_NONNULL_BEGIN
@interface oneViewController : UIViewController
@property(nonatomic,strong)DataModel *model;
@end
其次在OneVC.m里面写 网页视图 点击收藏显示添加成功
#import “oneViewController.h”
#import <WebKit/WebKit.h>
#import “Model.h”
@interface oneViewController ()
@property(nonatomic,strong)WKWebView *webview;
@end
@implementation oneViewController
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.webview=[[WKWebView alloc]initWithFrame:self.view.frame];
self.navigationItem.title=@“网页视图”;
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@“收藏” style:UIBarButtonItemStyleDone target:self action:@selector(click)];
[self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.url]]]];
[self.view addSubview:self.webview];
}
-(void)click{
[[Model initData]initSql];
[[Model initData]addData:self.model];
}
@end
最后一步创建TwoVC 是收藏的界面 里面显示收藏成功的数据 和一些删除数据的展示 在这里还可以运用自定义cell直接赋值 注册cell
#import “twoViewController.h”
#import “Model.h”
#import “TableViewCell.h”
@interface twoViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tab;
@property(nonatomic,strong)NSMutableArray *arr;
@end
@implementation twoViewController
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tab=[[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tab.delegate=self;
self.tab.dataSource=self;
[self.view addSubview:self.tab];
//注册cell
[self.tab registerNib:[UINib nibWithNibName:@“TableViewCell” bundle:nil] forCellReuseIdentifier:@“cell”];
self.arr=[[NSMutableArray alloc]init];
}
-(void)viewWillAppear:(BOOL)animated{
[[Model initData]initSql];
self.arr=[[Model initData]initeArr];
[self.tab reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arr.count;
1
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *oj=@“cell”;
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:oj];
DataModel *model=self.arr[indexPath.row];
self.tab.rowHeight=150;
cell.zhu.text=model.title;
cell.fu.text=model.mtime;
cell.img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.imgsrc]]];
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
[[Model initData]initSql];
[[Model initData]deletData:[self.arr[indexPath.row]classID]];
[self.arr removeObject:self.arr[indexPath.row]];
[self.tab reloadData];
}
@end
苹果自带地图
1.创建导航 在导航上创建定位按钮
2.引入两个依赖库 一个是地图的 一个是定位的
此处导两个库
在VC.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;
}