首先添加Core Location框架,可以通过该框架中包含的类,获取设备的地理位置.
使用位置服务时,需要添加coreLocation.framework
#impart <CoreLocation/CoreLocation.h>
注意事项:
1.使用地图服务时,会消耗更多的设备电量.因此,在获取到设备的位置后,应该停止定位以节省点亮
2.将位置服务设置为全局变量
.h文件中
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong,nonatomic) CLLocationManager *locationManager;
@end
.m文件中
//初始化位置服务
self.locationManager = [[CLLocationManager alloc]init];
//要求CLLocationManager对象返回全部的信息
[_locationManager setDistanceFilter:kCLDistanceFilterNone];
//设置定位经度
[_locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
//设置代理;
_locationManager.delegate = self;
//开始 实时定位
[_locationManager startUpdatingLocation];
执行的代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *newLocation = [locations objectAtIndex:0];
//获取新的经纬度
CLLocationCoordinate2D coordinate = newLocation.coordinate;
NSLog(@"经度:%f,纬度:%f",coordinate.longitude,coordinate.latitude);
[manager stopUpdatingLocation];
}
通过模拟器调试自定义位置.来获取当前位置
最终输出的结果是: