您的位置:首页 > 移动开发 > IOS开发

iOS CoreLocation 实现简单定位(现实城市)

2016-10-20 09:58 549 查看
 我们可能常常使用CoreLocation来实现很复杂的功能,包括地图显示、定位等等。但是在实际的项目开发中,我们可能有这样的需求,只要获取当前所在城市的名称即可,然后使用这个城市名称来开发其他的功能实现,并不需要地图等太复杂的功能。实现代码如下:

(1)因为涉及网络操作和定位功能,所以我们需要在Info.plist文件中加入如下字段:其中NSAppTransportSecurity和NSAllowArbitryLoads是由于Xcode7修改了关于网络访问的安全性而需要加入的。




(2)首先需要加入CoreLocation框架,然后由于我使用一个对话框弹出来显示当前城市,所以我把Main.storyboard也删除了。这样逻辑结构更为清晰。

(3)在AppDelegate.m中实现如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
ViewController * viewController = [[ViewController alloc] init];
[_window setRootViewController:viewController];
[_window makeKeyAndVisible];

return YES;

(4)在ViewController中实现如下:

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

//检测定位功能是否开启
if([CLLocationManager locationServicesEnabled]){

if(!_locationManager){

self.locationManager = [[CLLocationManager alloc] init];

if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];

}

//设置代理
[self.locationManager setDelegate:self];
//设置定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//设置距离筛选
[self.locationManager setDistanceFilter:100];
//开始定位
[self.locationManager startUpdatingLocation];
//设置开始识别方向
[self.locationManager startUpdatingHeading];

}

}else{
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil
message:@"您没有开启定位功能"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil nil];
[alertView show];
}
}

#pragma mark - CLLocationManangerDelegate
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

[self.locationManager stopUpdatingLocation];
CLLocation* location = locations.lastObject;

[self reverseGeocoder:location];
}

#pragma mark Geocoder
//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {

CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {

if(error || placemarks.count == 0){
NSLog(@"error = %@",error);
}else{

CLPlacemark* placemark = placemarks.firstObject;
NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"City"]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你的位置" message:[[placemark addressDictionary] objectForKey:@"City"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil nil];

[alert show];

}

}];
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: