使用系统的CoreLocation定位

//
//  ViewController.m
//  LBS
//
//  Created by tonnyhuang on 15/8/28.
//  Copyright (c) 2015tonnyhuang. All rights reserved.
//

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

//首先,我们需要在工程中导入CoreLocation系统框架。然后在我们的控制器中引入头文件。
//然后,声明一个CLLocationManager对象作为成员变量,用于定位获取经纬度坐标,并遵守协议CLLocationManager的协议。
@interface ViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
}

@end

@implementation ViewController



//实现其中的代理方法
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    //获取经度
    NSLog(@"经度 == %lf", newLocation.coordinate.longitude);
    //获取纬度
    NSLog(@"纬度 == %lf", newLocation.coordinate.latitude);
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编码出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark = [placemarks objectAtIndex:0];
        NSLog(@"%@", placemark.name);
        //获取城市
        NSString *city = placemark.locality;
       
        //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市
       
        if (!city) {
            city = placemark.administrativeArea;
        } else if (error == nil && [placemarks count] == 0){
            NSLog(@"no result were returned");
        } else if (error != nil) {
            NSLog(@"error = %@", error);
        }
        NSLog(@"city = %@", city);
    }];
    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
}



//最后在viewDidLoad中初始化定位管理器。
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeLocationService];
}

- (void)initializeLocationService {
    //初始化定位管理器
    _locationManager = [[CLLocationManager alloc] init];
    //设置代理
    _locationManager.delegate = self;
    //设置定位精确度到米     _locationManager.desiredAccuracy = kCLLocationAccuracyBest;     //设置过滤器为无     _locationManager.distanceFilter = kCLDistanceFilterNone;     //开始定位     [_locationManager requestAlwaysAuthorization];     //取得定位权限,有两个方法,取决于你的定位使用情况     [_locationManager startUpdatingLocation]; } //如果需要正常定位,相对iOS7而言,iOS8需要额外处理两个地方。//1. 工程的plist文件里面添加两个字段:NSLocationAlwaysUsageDescription,
//NSLocationWhenInUseUsageDescriptiontype类型均为string,值可以根据你的需要填写(也可以不填),填写的内容会展示在APP提示用户是否允许定位的alert内容里面,具体效果可以自行测试,这里就不额外截图。
 
这儿的位置不要错误  在上边的info.plist中添加字段
 

 
//2. 调用定位方法之前需要额外调用一个函数,直接在上面iOS7初始化定位服务的方法里面修改即可,具体如下:

// 开始定位
// 取得定位权限,有两个方法,取决于你的定位使用情况
// 一个是requestAlwaysAuthorization,一个是requestWhenInUseAuthorization
//[_locationManager requestAlwaysAuthorization];//这句话ios8以上版本使用。
//[_locationManager startUpdatingLocation];


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end