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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值