iOS 定位服务

iOS提供了四种不同的途径进行定位
(1)Wi-Fi,通过Wi-Fi路由器的地理位置信息查询,比较省电。iPhone、iPod touch和iPad都可以采用。
(2)蜂窝式移动电话基站,通过移动运营商基站定位。只有iPhone、3G版本的iPod touch和iPad可以采用。
(3)GPS卫星,通过GPS卫星位置定位,这种方式最为精准,单是耗电量大,不能遮挡。iPhone、iPod touche、iPad都可以采用。
(4)iBeacon微定位,苹果公司在iOS7后支持iBeacon技术。iBeacon技术是苹果研发的,它使用低功耗蓝牙技术,通过多个iBeacon基站创建一个信号区域,当设备进入该区域时,相应程序会提示用户进入这个区域。

Core Location框架

在iOS中,定位服务API主要使用Core Location框架,定位时主要使用CLLocationManager、CLLocationManagerDelegate和CLLocation这三个类。
(1)CLLocationManager,用于定位服务管理类,他能够给我们提供位置信息和高度信息,也可以监控设备进入或离开某个区域,还可以获得设备的运行方向。
(2)CLLocationManagerDelegate,是CLLocationManager类的委托协议。
(3)CLLocation,封装了位置信息和高度信息。
例:
Swift代码

// An highlighted block
//ViewController.swift文件
import UIKit
//引入CoreLocation模块
import CoreLocation
class ViewController:UIViewController,CLLocationManagerDelegate{
	//经度
	@IBOutlet weak var txtLng:UITextField!
	//纬度
	@IBOutlet weak var txtLat:UITextField!
	//高度
	@IBOutlet weak var txtAlt:UITextField!
	//定义CLLocationManager类型的locationManager属性
	var locationManager:CLLocationManager!

	override func viewDidLoad(){
		super.viewDidLoad()
		
		//定位服务管理对象初始化
		//创建并初始化locationManager属性
		self.locationManager=CLLocationManager()
		//设置定位服务委托对象为self
		self.locationManager.delegate=self
		/*desiredAccuracy属性,取值有6个常量:
		(1)kCLLocationAccuracyNearestTenMeters,精确到10米
		(2)kCLLocationAccuracyHundredMeters,精确到100米
		(3)kCLLocationAccuracyKilometer,精确到1000米
		(4)kCLLocationAccuracyThreeKilometers,精确到300米
		(5)kCLLocationAccuracyBest,使用电池供电时最高的精度
		(6)kCLLocationAccuracyBestForNavigation,导航情况下最高的精度,一般有外界电源时使用
		*/
		self.locationManager.desiredAccuracy=KCLLocationAcuracyBest
		//设置distanceFilter属性,它是距离过滤器,定义设备移动后获得位置信息的最小距离,单位是米。
		self.locationManager.distanceFilter=100.0
		//iOS8新添加的,弹出用户授权对话框,为了能弹出授权对话框,需要修改工程配置info.plist属性列表,添加NSLocationAlwaysUsageDescription和NSLocationWhenInUserUsageDescription键
		//要求用户“使用应用期间”授权
		self.locationManager.requestWhenInUseAuthorization()
		//要求用户“始终”授权
		self.locationManager.requestAlwaysAuthorization()
		//开始定位
		self.locationManager.startUpdatingLocation()
	}
	override func viewWillDisappear(_ animated:Bool)
	{
		super.viewWillDisappear(animated)
		//停止定位
		self.locationManager.stopUpdatingLocation()
	}
	//定位成功,locations是位置变化的集合,它按照时间变化的顺序存放。如果要获得当前设备的位置,可以取集合最后一个元素
	func locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[Cllocation]){
		//获取当前设备位置信息
		var currlocation=locations[locations.count-1] as CLLocation
		//获取纬度
		self.txtLat.text=String(format:"%3.5f",currLocation.coordinate.latitude)
		//获取经度
		self.txtLng.text=String(format:"%3.5f",currLocation.coordinate.longitude)
		//获取高度
		self.txtAlt.text=String(format:"%3.5f",currLocation.altitude)
	}
	//定位失败
	func locationManager(_ manager:CLLocationManager!,didFailWithError error:NSError!){
		print("error:\(error.localizedDescription)")
	}
	//授权状态发生变化时调用
	func locationManager(_ manager:CLLocationManager,didChangeAuthorizationStatus status:CLAuthorizationstatus){
		switch status{
		case .authorizedAlways:
			print("已经授权")
		case .authorizedWhenInUse:
			print("使用时授权")
		case .denied:
			print("拒绝")
		case .restricted:
			print("受限")
		case .notDetermined:
			print("用户还没有确定")
		}
	}
}

ObjectiveC代码

// An highlighted block
//ViewController.m文件
#import "ViewController.h"
#import 

@interface ViewController()<CLLocationManagerDelegate>
//经度
@property(weak,nonatomic) IBOutlet UITextField *txtLng;
//纬度
@property(weak,nonatomic) IBOutlet UITextField *txtLat;
//高度
@property(weak,nonatomic) IBOutlet UITextField *txtAlt;
//定义CLLocationManager类型的locationManager属性
@property(nonatomic,strong)CLLocationManager *locationManager;
@end
@imlementation ViewController
-(void)viewDidLoad{
	[super viewDidLoad];
	//定位服务管理对象初始化
	//创建并初始化locationManager属性
		self.locationManager=[[CLLocationManager alloc] init];
		//设置定位服务委托对象为self
		self.locationManager.delegate=self;
		/*desiredAccuracy属性,取值有6个常量:
		(1)kCLLocationAccuracyNearestTenMeters,精确到10米
		(2)kCLLocationAccuracyHundredMeters,精确到100米
		(3)kCLLocationAccuracyKilometer,精确到1000米
		(4)kCLLocationAccuracyThreeKilometers,精确到300米
		(5)kCLLocationAccuracyBest,使用电池供电时最高的精度
		(6)kCLLocationAccuracyBestForNavigation,导航情况下最高的精度,一般有外界电源时使用
		*/
		[self.locationManager KCLLocationAccuracyBest];
		[self.locationManager requestAlwaysAuthorization];
		//开始定位
		[self.locationManager startUpdatingLocation];
}
-(void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
	//停止定位
	[self.locationManager stopUpdatingLocation];
}
//定位成功,locations是位置变化的集合,它按照时间变化的顺序存放。如果要获得当前设备的位置,可以取集合最后一个元素
-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray*)locations{
	CLLocation *currLocation=[locations lastObject];
	self.txtLat.text=[NSString stringWithFormat:@"%3.5f",currlocation.coordinate.latitude];
	self.txtLng.text=[NSString stringWithFormat:@"%3.5f",currlocation.coordinate.longitude];
	self.txtAlt.text=[NSString stringWithFormat:@"%3.5f",currlocation.coordinate.altitude];
}
//定位失败
-(void)locationManager:(CLLocationManager*)manager didFailWithError:(NSError*)error{
	NSLog(@"error:%@",error);
}
//授权状态发生变化时调用
-(void)locationManager:(CLLocationManager*)managerdidChangeAuthorizationStatus:(CLAuthorizationStatus)status{
	if(status==KCLAuthorizationStatusAuthorizedAlways){
		NSLog(@"已经授权");
	}else if(status==KCLAuthorizationStatusAuthorizedWhenInUse){
		NSLog(@"使用时授权");
	}else if(status==KCLAuthorizationStatusDenied){
		NSLog(@"拒绝");
	}else if(status==KCLAuthorizationStatusRestricted){
		NSLog(@"受限");
	}else if(status==KCLAuthorizationStatusNotDetermined){
		NSLog(@"用户还没有确定");
	}
}
@end
定位服务管理

1、应用启动与停止下的定位服务管理
默认情况下,定位服务是可以在后台运行的,例如车载导航应用、健身类型应用,都需要在后台运行很长时间。
启动定位服务,而没用停止定位夫妇,我们可以在视图控制器的didReceiveMemoryWarning(内存警告、内存不足)方法中停止定位服务。
我们也可以在应用程序委托对象AppDelegate的application:didFinishLaunchingWithOptions:方法中开启服务,在applicationDidReceiveMemoryWarning:或applicationWillTerminate:(即将终止)中停止服务
例:
Swift代码

// An highlighted block
override func viewDidLoad(){
	super.viewDidLoad()
	//开始定位
	self.locationManager.startUpdatingLocation()
}
//内存警告、内存不足
override func didReceiveMemoryWarning(){
	super.didReceiveMemoryWarning()
	//停止定位
	self.locationManager.stopUpdatingLocation()
}

ObjectiveC代码

// An highlighted block
-(void)viewDidLoad{
	[super viewDidLoad];
	//开始定位
	[self.locationManager startUpdatingLocation];
}
//内存警告、内存不足
-(void)didReceiveMemoryWarning{
	[super didReceiveMemoryWarning];
	//停止定位
	[self.locationManager stopUpdatingLocation];
}

2、视图切换下的定位服务管理
有些应用需要在地图上显式用户的位置,当视图可见时,应用开启定位服务,当视图不可见时停止定位服务。
例:
Swift代码

// An highlighted block
override func viewWillAppear(_ animated:Bool){
	super.viewWillAppear(animated)
	//开启定位
	self.locationManager.startUpdatingLocation()
}
override func viewWillDisappear(_ animated:Bool){
	super.viewWillDisappear(animated)
	//停止定位
	self.locationManager.stopUpdatingLocation()
}

ObjectiveC代码

// An highlighted block
-(void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	//开始定位
	[self.locationManager startUpdatingLocation];
}
-(void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
	//停止服务
	[self.locationManager stopUpdatingLocation];
}

3、应用前后台切换下的定位服务管理
很多机遇位置服务的应用,在进入前台时 自动定位服务,在退到后台时停止定位服务。
启动和停止服务有很多种,如果一个应用中有多个界面要获取定位信息,定位服务可以在应用程序委托对象AppDelegate中进行,位置发生变化,通知所有显示定位信息的页面,这需要在相应的视图中注册观察位置的通知。
本地通知说明:转载https://www.jianshu.com/p/5a05537435d8
例:
Swift代码

// An highlighted block
//AppDelegate.swift文件
let UpdateLocationNotification="KUpdateLocationNotification"
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate:UIResponder,UIAPPlicationDelegate,CLLocationManagerDelegate{
	var window:UIWindow?
	var locationManager:CLLocationManager!
	func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey:Any]?)->Bool{
		//定位服务
		self.locationManager=CLLocationManager()
		self.locationManager.delegate=self
		self.locationManager.desiredAccuracy=KCLLocationAccuracyBest
		self.locationManager.distanceFilter=1000.0
		self.locationManager.requestWhenInUseAuthorization()
		self.locationManager.requestAlwaysAuthorization()
		return true
	}
	//应用启动的过程中(包括从后台恢复时),都会调用
	func applicationDidBecomeActive(_ application:UIAppliation){
		//开始定位
		self.locationManager.startUpdatingLocation()
	}
	//应用退到后台时调用
	func applicationDidEnterBackground(_ application:UIApplication){
		//停止定位
		self.locationManager.stopUpdatingLocation()
	}
	#MARK:--Core Location委托方法用于实现位置更新
	func locationManager(_ manager:CLLocationManager,didUpdateLocations location:[CLLocation]){
		let currLocation=locations.last! as CLLocation
		NotificationCenter.default.post(name:Notification.Name(rawValue:UpdateLocationNotification),object:currLocation)
	}
	func locationManager(_ manager:CLLocationManager,didFailWithError error:NSError){
		print("error:\(error.localizedDescription)")
	}
	func locationManager(_ manager:CLLocationManager,didChangeAuthorization status:CLAuthorizationStatus){
			switch status{
			case .authorizedAlways:
				print("已经授权")
			case .authorizedWhenInUse:
				print("使用时授权")
			case .denied:
				print("拒绝")
			case .restricted:
				print("受限")
			case .notDetemined:
				print("用户没有确定")
			}
	}
}

//ViewController.swift文件
import UIKit
import CoreLocation

class ViewController:UIViewController{
	//经度
	@IBOutlet weak var txtLng:UITextField!
	//纬度
	@IBOutlet weak var txtLat:UITextField!
	//高度
	@IBOutlet weak var txtAlt:UITextField!
	override func viewDidLoad(){
		super.viewDidLoad()
		NotificationCenter.defalt.addObserver(self,selector:#selector(updateLocation(_:)),name:Notification.Name(rawValue:UpdateLocationNotification,object:nil))
	}
	override func didReceiveMenoryWarming(){
		super.didReceiveMemoryWarning()
		NotificationCenter.default.removeObserver(self)
	}
	//接收位置变化通知
	func updateLocation(_ notification:NSNotification){
		let currLocation=notification.object as! CLLocation 	self.txtLat.text=String(format:"%3.5f",currLocation.coordinate.latitude)
		self.txtLng.text=String(format:"%3.5f",currLocation.coordinate.longitude)
		self.txtAlt.text=String(format:"%3.5f",currLocation.altitude)
	}
}

ObjectiveC代码

// An highlighted block
//AppDelegate.m文件
#import "AppDelegate.h"
#import 
#define UpdateLocationNotification @"KUpdateLocationNotification"
@interface AppDelegate()<CLLocationManagerDelegate>
@property(nonatiomic,strong) CLLocationManager *locationManager;
@end
@implementation AppDelegate
-(BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
	//定位服务
	self.locationManager=[[CLLocationManager alloc] init];
	self.locationManager.delegate=self;
	self.locationManager.desiredAccuracy=KCLLocationAccuracyBest;
	self.locationManager.distanceFilter=1000.0;
	[self.locationManager requestWhenInUseAuthorization];
	[self.locationManager requestAlwaysAuthorization];
}
-(void)applicationDidBecomeActive:(UIApplication*)application{
	//开始定位
	[self.locationManager startUpdatingLocation];
}
-(void)applicationDidEnterBackground:(UIApplication*)application{
	//停止定位
	[self.locationManager stopUpdatingLocation];
}
#pragma mark -- Core Location委托方法用于实现位置的更新
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray*)locations{
	CLLocation* currlocation=[locations lastObejct];
	//将位置信息通过通知同送给显示位置信息的视图控制器
	[[NSNotiffcationCenter defaultCenter] postNotificationName:UpdateLocationNotification object:currLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError*)error{
	NSLog(@"error:%@",error);
}
-(void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
	if(status==KCLAuthorizationStatusAuthorizedAlways){
		NSLog(@"已经授权");
	}else if(status==KCLAuthorizationStatusAuthorizedWhenInUse){
		NSLog(@"使用时授权");
	}else if(status==KCLAuthorizationStatusDenied){
		NSLog(@"拒绝");
	}else if(status==KCLAuthorizationStatusRestricted){
		NSLog(@"受限");
	}else if(status==KCLAuthorizationStatusNotDetermined){
		NSLog(@"用户还没有确定");
	}
}

//ViewController.m文件
#import "ViewController.h"
#import 
#define UpdateLocationNotification @"KUpdateLocationNotification"
@interface ViewController()
//经度
@property(weak,nonatomic) IBOutlet UITextField *txtLng;
//纬度
@property(weak,nonatomic) IBOutlet UITextField *txtLat;
//高度
@property(weak,nonatomic) IBOutlet UITextField *txtAlt;
@end
@implementaion ViewController
-(void)viewDidLoad{
	[super viewDidLocad];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLocation:) name:UpdateLocationNotification object:nil];
}
-(void)didReceiveMemoryWarning{
	[super didReceiveMemoryWarning];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)updateLocation:(NSNotification*)notification{
	CLLocation *currLocation=[notification object];
	self.txtLat.text=[NSString stringWithFormat:@"%3.5f",currLocation.coordinate.latitude];
	self.txtLng.text=[NSString stringWithFormat:@"%3.5f",currLocation.coordinate.longitude];
	self.txtAlt.text=[NSString stringWithFormat:@"%3.5f",currLocation.coordinate.altitude];
}
@end

4、设置自动暂停位置服务
iOS6之后CLLocationManager类新增pausesLocationUpdatesAutomatically属性,他能设置自动暂停位置服务,定位服务的开启和暂停管理权交给系统,这样会更加合理和简单。
设置自动暂停位置服务的功能,可以通过设置pausesLocationUpdatesAutomatically属性实现,也可以设置activityType属性实现。activityType是应用活动类型,activityType是美剧类型CLActivetyType。
Swift枚举成员:
other,默认值,位置的类型
automotiveNavigation,车载导航类型,位置变化快
fitness,不行导航类型,位置变化慢
otherNavigation,其他导航类型,位置变化适中

ObjectiveC枚举成员:
CLActivityTypeOther,默认值,位置的类型
CLActivityTypeAutomotiveNavigation,车载导航类型,位置变化快
CLActivityTypeFitness,不行导航类型,位置变化慢
CLActivityTypeOtherNavigation,其他导航类型,位置变化适中

Swift代码
//设置自动暂停位置服务
self.locationManager.pausesLocationUpdatesAutoMatically=true
self.locationManager.activityType=.automotiveNavigation

ObjectiveC代码
//设置自动暂停位置服务
self.locationManager.pausesLocationUpdatesAutoMatically=TRUE;
self.locationManager.activityType=CLActivityTypeOtherNavigation;

5、后台位置服务管理
首先需要开启支持应用后台运行的模式。在Xcode工程中选择Capabilities->Background Modes->Location updates。
Swift代码
self.locationManager.allowsBackgroundLocationUpdates=true
ObjectiveC代码
self.locationManager.allowsBackgroundLocationUpdates=true;
该属性设置为true,表示可以在后台运行,false表示不能,默认值是false。

地理信息编码与反编码

地理信息饭编码
地理信息反编码就是根据给定地点的地理坐标,返回这个地点的相关文字描述信息,这些文字描述被封装在CLPlacemark类中,此类叫“地标”类。属性如下:
(1)name,有关地址的名字属性
(2)addressDictionary,地址信息的字典,包含一些键值对,其中的键是在AddressBook.framework(地址簿框架)中定义好的。
(3)ISOcountryCode,ISO国家代号
(4)country,国家信息
(5)postalCode,邮政编码
(6)administrativeArea,行政区域信息
(7)subAdministrativeArea,行政区域附加信息
(8)locality指定城市信息
(9)subLocality,指定城市信息附加信息
(10)thoroughfare,指定街道级别信息
(11)subThoroughfare指定街道级别的附加信息
地理信息反编码使用CLGeocoder类实现,这个类能够实现在地理坐标与地理文字描述信息之间的转换。CLGeocoder类中进行地理信息反编码的方法如下:
Swift代码
func reverseGeocodeLocation(_ location:CLLocation,completionHandler completionHandler:CLGeocodeCompletionHandler)

ObjectiveC代码
-(void)reverseGeocodeLocation:(CLLocation*)location completionHandler:(CLGeocodeCompletionHandler)completionHandler

location是要定位的地理位置对象,completionHandler参数指定了一个代码块CLGeocodeCompletionHandler对象,用于地理信息反编码后的回调。
例:
Swift代码

// An highlighted block
//ViewController.swift文件
@IBAction func reverseGeocode(_ sender:AnyObject){
	//地理信息编码,self.currLocation是CLLocation类型的属性,他是在委托方法locationManager:didUpdateLocations:中初始化的。completionHandler:中,参数placemarks是返回的地标结合。一个地理坐标泛指一个范围,在这个范围中可能有多重不同的描述信息,这些信息被放在地标集合中。参数error描述了出错信息,如果error非空,说明饭编码失败。
	let geocoder=CLGeocoder()
	geocoder.reverseGeocodeLocation(self.currLocation,completionHandler:{(placemarks,error)->Void in
		if error !=nil{
			print(error!.localizedDescription)
		//判断地标集合的长度大于0的情况,表示反编码成功并有返回的描述信息
		}else if placemarks!=nil && placemarks!.count>0{
			//取出一个地标CLPlacemark对象,如果想要查看所有地标信息,玄幻遍历即可。
			let placemark=placemarks!{0}
			//取出地标对象的name属性
			let name=placemark.name
			self.txtView.text=name
		}
	})
}

ObjectiveC代码

// An highlighted block
//ViewController.m文件
-(IBAction)reverseGeocode:(id)sender{
	CLGeocoder *geocoder=[[CLGeocoder alloc] init];
	//地理信息编码,self.currLocation是CLLocation类型的属性,他是在委托方法locationManager:didUpdateLocations:中初始化的。completionHandler:中,参数placemarks是返回的地标结合。一个地理坐标泛指一个范围,在这个范围中可能有多重不同的描述信息,这些信息被放在地标集合中。参数error描述了出错信息,如果error非空,说明饭编码失败。
	[geocoder reverseGeocodeLocation:self.currLocation completionHandler:^(NSArray<CLPlacemark*> *placemarks,NSError *error){
		if(error){
			NSLog(@"Error is %@",error.localizedDescription);
		//判断地标集合的长度大于0的情况,表示反编码成功并有返回的描述信息
		}else if([placemarks count]>0){
			//取出一个地标CLPlacemark对象,如果想要查看所有地标信息,玄幻遍历即可。
			CLPlacemark *placemark=placemarks[0];
			//取出地标对象的name属性
			NSString *name =placemark.name;
			self.txtView.text=name;
		}
	}];
}

地理信息编码查询
编码查询与反编码刚好相反,给定的是地理信息的文字描述 ,查询出相关的地理坐标,这种查询结果也是一个合集。
地理信息编码查询也是采用CLGeocoder类,有关地理信息编码的方法如下:
(1)geocodeAddressDictionary:completionHandler,通过指定一个地址信息字典对象参数进行查询。
(2)geocodeAddressString:completionHandle,通过制定一个地址字符串参数进行查询。
(3)geocodeAddressString:inRegion:completionHandler,通过制定地址字符串和查询范围作为参数进行查询,其中inRegion部分的参数是指定的查询范围,他是CLRegion类型。
例:
Swift代码

// An highlighted block
@IBAction func geocodeQuery(_ sender:AnyObject){
	if self.txtQueryKey.text==nil{
		return
	}
	//未指定查询范围
	//进行地理信息编码查询,查询结果保存到placemarks中,它是数值类型,取出集合中的第一个地标对象。
	let geocoder=GLGeocoder()
	geocoder.geocodeAddressString(self.txtQuerKey.text!,completionHandler:{(placemarks,error)->Void in
		if error!=nil{
			print("\(error?.localizedDescription)")
		}else if placemarks!.count>0{
			//获取第一个地标对象
			let placemark=placemarks![0] as CLPlacemark
			let name=placemark.name!
			//获取经纬度信息
			let location=placemark.location!
			let lng=location.coordinate.longitude
			let lat=location.coordinate.latitude
			self.txtView.tet=String(format:"经度:%3.5f\n纬度:%3.5f\n%@",lng,lat,name)
		}
	})
	/*
	//指定查询范围
	//常见一个CLLocation对象,该对象查询范围中心点。
	let location=CLLocation(latitude:40.382848,longitude:117.747373)
	//构造一个圆形区域对象CLCircularRegion,其构造函数为initWithCenter:radius:identifier:,参数1是指定区域的中心点,类型是CLLocationCoordinate2D;参数2radius指定区域半径单位为米;参数3identifier用于为区域指定一个标识,保证在你的应用中是惟一的,这个参数不能为空
	let region=CLCircularRegion(center:location.coordinate,radius:5000,identifier:"GeocodeRegion")
	let geocoder=CLGeocoder()
	geocoder.geocodeAddressString(self.txtQueryKey.text!,in:region,completionHandler:{(placemarks,error)->Void in
		//TODO
	})
	*/
	//关闭键盘
	self.txtQueryKey.resignFirestResponder()
}

ObjectiveC代码

// An highlighted block
-(IBAction)geocodeQuery:(id)sender{
	if(self.txtQueryKey.text=nil){
		return;
	}
	//未指定查询范围
	//进行地理信息编码查询,查询结果保存到placemarks中,它是数值类型,取出集合中的第一个地标对象。
	CLGeocoder *geocoder=[[CLGeocoder alloc] int];
	[geocoder geocodeAddressString:self.txtQueryKey.text completionHandler:^(NSArray<CLPlacemark *>*placemarks,NSError *error){
		if(error){
			NSLog(@"Error is %@",error.localizedDescription);
		}else if([placemarks count]>0){
			//获取第一个地标对象
			CLPlacemark* placemark=placemarks[0];
			NSString *name=placemark.name;
			//获取经纬度信息
			CLLocation *location=placemark.location;
			double lng=location.coordinate.longitude;
			double lat=location.coordinate.latitude;
			self.txtVeiw.text=[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f\n%@",lng,lat,name];
		}
	}];
	/*
	//指定查询范围
	//常见一个CLLocation对象,该对象查询范围中心点。
	CLLocation *location=[[CLLocation alloc] initWithLatitude:40.384848 longitude:117.848384];
	//构造一个圆形区域对象CLCircularRegion,其构造函数为initWithCenter:radius:identifier:,参数1是指定区域的中心点,类型是CLLocationCoordinate2D;参数2radius指定区域半径单位为米;参数3identifier用于为区域指定一个标识,保证在你的应用中是惟一的,这个参数不能为空
	CLCircularRegion* region=[[CLCircularRegion alloc] initWithCenter:location.coordinate radius:5000 identifier:@"GeocodeRegion"];
	[geocoder geocodeAddressString:self.txtQueryKey.text inRegion:region completionHandler:^(NSArray*placemarks,NSError *error){
		//TODO
	}];
	*/
	//关闭键盘
	[self.txtQueryKey resignFirstResponder];
}

参考资料
《IOS开发指南 从HELLO WORLD到APP STORE上架 第5版》

你可能感兴趣的:(ios)