今天我们要做的是一个地图和网络数据解析的工程
首先打开cocopods,导入
pod ‘YYModel’
pod ‘AFNetworking’
我用的MVC的设计模式
首先创建三个文件夹
这里我就把我自己创建的类给大家说一声
在Model里面创建
Model.h
Model.m
然后在View文件夹创建
MYTableViewCell.m
MYTableViewCell.h
这需要勾选上一个xib文件
我们直接在里面创建两个label方便我们的写入
然后Controller里面需要创建一个
NextViewController.m
NextViewController.h
和我们自带的ViewController
好了,创建完成之后,我们开始写代码
首先是Viewcontroller里面的
#import "ViewController.h"
//引入头文件 '地图框架'
#import <MapKit/MapKit.h>
//引入头文件 ‘定位框架’
#import <CoreLocation/CoreLocation.h>
#import "NextViewController.h"
@interface ViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>//地图视图协议
//定义属性 ‘地图视图’
@property(nonatomic,strong)MKMapView *MapView;
//定义属性 ‘地理位置管理者’
@property(nonatomic,strong)CLLocationManager *locManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//导航标题 显示当前省会
self.navigationItem.title = @"违章查询";
//初始化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];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"定位" style:UIBarButtonItemStyleDone target:self action:@selector(currentBtnDidPress:)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"查询" style:UIBarButtonItemStyleDone target:self action:@selector(right)];
}
//获取当前按钮触发
-(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<MKAnnotation>)annotation{
//静态字符串标识
static NSString *iden = @"pin";
//初始化描点视图
MKPinAnnotationView *pin = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:iden];
//设置掉落状态
pin.animatesDrop = YES;
//设置泡泡效果
pin.canShowCallout = YES;
return pin;
}
-(void)right{
NextViewController *next = [NextViewController new];
[self.navigationController pushViewController:next animated:YES];
}
@end
我直接把我自己的代码拿过来了,具体的我会在里面加注释
需要在Appdelegate里面设置一个
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ViewController new]];
然后是我们创建的NextViewController.m里面
#import "NextViewController.h"
#import "Model.h"
#import <AFNetworking.h>
#import <YYModel.h>
#import "MYTableViewCell.h"
@interface NextViewController ()<UITableViewDelegate,UITableViewDataSource>
{
Model *mod;
}
@property(nonatomic,strong)UITableView *tbv;
@property(nonatomic,strong)NSMutableArray *DataArr;
@end
@implementation NextViewController
- (UITableView *)tbv{
if (!_tbv) {
_tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
_tbv.delegate = self;
_tbv.dataSource = self;
[_tbv registerNib:[UINib nibWithNibName:@"MYTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
}
return _tbv;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.DataArr = [NSMutableArray array];
[self.view addSubview:self.tbv];
[self loadData];
}
//实现网络请求与解析的方法
-(void)loadData{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *dic=@{@"lat":@"40.041478",@"lon":@"116.300267",@"key":@"6d96ee265cc090b418ee51257ff9c48f"};
[manager POST:@"http://v.juhe.cn/wzpoints/query" parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"解析成功");
NSLog(@"解析的数据=====================%@",responseObject);
self->mod = [Model yy_modelWithJSON:responseObject];
NSLog(@"model ============== %@",self->mod);
[self.tbv reloadData];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"解析失败");
}];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return mod.result.list.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MYTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
_tbv.rowHeight = 80;
[cell loadDataForModel:[mod.result.list objectAtIndex:indexPath.row]];
return cell;
}
@end
然后是MYTableViewCell.h里面
#import <UIKit/UIKit.h>
#import "Model.h"
NS_ASSUME_NONNULL_BEGIN
@interface MYTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *Lab1;
@property (weak, nonatomic) IBOutlet UILabel *Lab2;
-(void)loadDataForModel:(Model *)mod;
@end
NS_ASSUME_NONNULL_END
这里面的两个属性,Lab1,和Lab2,是我们用xib文件拖进去的
然后是MYTableViewCell.m
#import "MYTableViewCell.h"
@implementation MYTableViewCell
- (void)loadDataForModel:(ThreeModel *)mod{
self.Lab1.text = mod.title;
self.Lab2.text = [NSString stringWithFormat:@"%@,%@,%@",mod.detail,mod.address,mod.city];
}
@end
最后是Model.m
#import "Model.h"
@implementation ThreeModel
@end
@implementation TwoModel
// 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"list" : [ThreeModel class]};
}
@end
@implementation Model
// 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。
+ (NSDictionary *)modelContainerPropertyGenericClass {
return @{@"result" : [TwoModel class]};
}
@end
Model.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ThreeModel : NSObject
@property(nonatomic,strong)NSString *address;
@property(nonatomic,strong)NSString *city;
@property(nonatomic,strong)NSString *detail;
@property(nonatomic,strong)NSString *title;
@end
@interface TwoModel : NSObject
@property(nonatomic,strong)NSArray *list;
@end
@interface Model : NSObject
@property(nonatomic,strong)NSString *reason;
@property(nonatomic,strong)TwoModel *result;
@end
NS_ASSUME_NONNULL_END
到这我们基本就已经完成了