1.導入框架
<pre>
import <CoreLocation/CoreLocation.h>
</pre>
2.定義對象
<pre>
@property(nonatomic,strong)CLLocationManager *locationManager;
</pre>
3.開始定位
<pre>
//定位服務
-(void)LocationService
{
if ([CLLocationManager locationServicesEnabled]) {
// 初始化定位管理器
self.locationManager=[[CLLocationManager alloc]init];
self.locationManager.delegate=self;
// 設置定位精確度到千米
self.locationManager.desiredAccuracy=kCLLocationAccuracyKilometer;
// 設置過濾器為無
self.locationManager.distanceFilter=kCLDistanceFilterNone;
//這句話ios8以上版本使用
[ self.locationManager requestAlwaysAuthorization];
//開始定位
[ self.locationManager startUpdatingLocation];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"無法定位" message:@"請檢查你的設備是否開啟定位功能" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alert show];
}
}
</pre>
4.代理方法
<pre>
pragma mark--定位代理
-
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{// 獲取當前所在的城市名
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//根據經緯度反向地理編譯出地址信息
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray*array, NSError *error){
if (array.count > 0){
CLPlacemark *placemark = [array objectAtIndex:0];//獲取城市 NSString \*city = placemark.locality; if (!city) { //四大直轄市的城市信息無法通過locality獲得,只能通過獲取省份的方法來獲得(如果city為空,則可知為直轄市) city = placemark.administrativeArea; } NSLog(@"city = %@", city); self.cityLabel.text=city;
//
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
//系統會一直更新數據,直到選擇停止更新,因為我們只需要獲得一次經緯度即可,所以獲取之后就停止更新
[manager stopUpdatingLocation];
}
</pre>