IOS 用内置代码获取定位信息

xxx.h:
#import <UIKit/UIKit.h>
#import "BaseViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController : BaseViewController<CLLocationManagerDelegate>

@property(nonatomic,retain) CLLocationManager* locationManager;

- (IBAction)onSubmit:(UIButton *)sender;

@end


xxx.m:
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@implementation ViewController

@synthesize locationManager;

- (void)viewDidLoad{
    [super viewDidLoad];
    
        // 判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        locationManager = [[CLLocationManager alloc] init];
//        locationManager.distanceFilter = 1; //设置距离筛选器distanceFilter,表示设备至少移动1000米,才通知委托更新
        locationManager.distanceFilter = kCLDistanceFilterNone;   //这是默认,就是不做这个限制,可能会不断更新


        locationManager.delegate = self;

        // 开始定位
        [locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
    }
}

-(void) viewDidUnload{
    [LogUtil d:@"viewDidUnload"];
    [self.locationManager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    CLLocationCoordinate2D coord = currentLocation.coordinate;
//    [LogUtil d:@"%f",coord.latitude];
//    [LogUtil d:@"%f",coord.longitude];
    //[self.locationManager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//    [LogUtil d:@"%f",newLocation.coordinate.latitude];
//    [LogUtil d:@"%f",newLocation.coordinate.longitude];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
    }
}

@end

猜你喜欢

转载自iaiai.iteye.com/blog/2115204