从零开始系列之iOS地图获取当前城市



发现之前的地图获取当前地理位置信息在Deprecated in iOS 5.0。已经被苹果弃之不用了。推荐

使用CLGeocoder来替代。发现非常简单,比之前写的方法简单了不少。
地图的前提是你导入了MapKit这个库
#import <MapKit/MKMapView.h>

先声明一个全局的CLLocationManager对象。
 CLLocationManager *_currentLoaction;

之后开启定位功能。
_currentLoaction = [[CLLocationManager alloc] init];
_currentLoaction.delegate = self;
[_currentLoaction startUpdatingLocation];

定位结束之后更新当前的地址经纬度等信息。

#pragma mark - Location 
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_currentLoaction stopUpdatingLocation];
    
    NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    
    [_geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        _placeMark = [placemarks objectAtIndex:0];
        _locationLabel.text = _placeMark.administrativeArea;
        ITTDINFO(@"%@",_locationLabel.text);
        // we have received our current location, so enable the "Get Current Address" button
    }];
}
解释

_geocoder 这个是我先要声明的CLGeocoder。使用之前要alloc,才能使用。
我刚开始犯了一个低级错误,没有在viewDidLoad方法中_geocoder = [[CLGeocoder alloc] init];导致一直nil无法出现block的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值