定位定不出来解决方案
主要问题
1.没有使用Strong属性
2.检查plist是否配置正确
3.模拟器bug—–>设置虚拟位置
解决方案
引入CoreLocation.framework包
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong)CLLocationManager *locationManager;
@property (nonatomic,strong)UILabel *locationLabel;
@property (nonatomic,strong)UILabel *cityLabel;
@property (nonatomic,copy)NSString *city;
创建LocationManager的方法,在需要定位的地方调用即可
- (void)initializeLocationService {
//位置管理器
self.locationManager=[[CLLocationManager alloc]init];
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"定位服务当前可能尚未打开,请设置打开!");
return;
}
//如果没有授权则请求用户授权
if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
// 2.手动请求授权(IOS8以后,必须授权)
// 当用户使用的时候授权---->当能看见你程序界面的时候
[self.locationManager requestWhenInUseAuthorization];
}
//设置代理
self.locationManager.delegate=self;
//定位频率,每隔多少米定位一次
//位置筛选器--->当位置发生一定变化之后调用代理方法-->降低代理方法的调用频率,省电
self.locationManager.distanceFilter=10.0;
//设置精准度
self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
//开始定位
[self.locationManager startUpdatingLocation];
}
执行[self.locationManager startUpdatingLocation]后会频繁调用下面的代理方法,需调用[_locationManager stopUpdatingLocation]来停止调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location=[locations firstObject];//取出第一个位置
CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
self.locationLabel.text = [NSString stringWithFormat:@"经度:%f,纬度:%f",coordinate.longitude,coordinate.latitude];
//反地理编码(根据经纬度获取位置信息(位置所在国家,城市))
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark=[placemarks firstObject];
// NSLog(@"city:%@",placemark.locality);
self.city = placemark.locality;
if (!self.city) {
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
self.city = placemark.administrativeArea;
}
self.cityLabel.text = self.city;
NSLog(@"city = %@", self.city);
}];
//如果不需要实时定位,使用完即使关闭定位服务
[_locationManager stopUpdatingLocation];
}
配置plist文件
此处转载:http://www.tuicool.com/articles/VN3632
新增Key: NSLocationAlwaysUsageDescription 或NSLocationWhenInUseUsageDescription ,这两个Key的值将分别用于描述应用程序始终使用和使用期间使用定位的说明,这些说明将显示在用户设置中
如果真机测试,就可以定位出来了,模拟器则需要添加虚拟位置
点击模拟器,然后按照下图操作就可以设置虚拟位置了
搞定!