环境:
I5、4G
Win7旗舰版 64
Vm 8.0
Mac OS X Lion 10.7.2 VMware Image
Xcode 4.3
IOS SDK 5.0
I5、4G
Win7旗舰版 64
Vm 8.0
Mac OS X Lion 10.7.2 VMware Image
Xcode 4.3
IOS SDK 5.0
Ipad2 5.1.1
要利用CoreLocation,必须在frameworks里面加入“CoreLocation.framework”。在最新版本的Xcode(4.x)中加入新的framework步骤如下:
单击项目的target =>在出来的xcodeproj面板中点击“Link Binary With Libraries” =>点击“+”,然后选择需要的framework即可。
首先建立一个Single View Application工程,然后引入CoreLocation.framework,并在ViewController.h中修改如下:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface XViewController : UIViewController
{
CLLocationManager *locManager;
}
@property (retain, nonatomic) IBOutlet UILabel *lonLabel;
@property (retain, nonatomic) IBOutlet UILabel *latLabel;
@property (retain, nonatomic) CLLocationManager *locManager;
- (IBAction)StartLocation:(id)sender;
@end
.m文件的实现如下,具体解释在代码注释中说明
- (void)dealloc {
[lonLabel release];
[latLabel release];
[locManager release];
[super dealloc];
}
//协议中的方法,作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//结构体,存储位置坐标
CLLocationCoordinate2D loc = [newLocation coordinate];
float longitude = loc.longitude;
float latitude = loc.latitude;
self.lonLabel.text = [NSString stringWithFormat:@"%f",longitude];
self.latLabel.text = [NSString stringWithFormat:@"%f",latitude];
}
//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSString *errorMsg = nil;
if ([error code] == kCLErrorDenied) {
errorMsg = @"访问被拒绝";
}
if ([error code] == kCLErrorLocationUnknown) {
errorMsg = @"获取位置信息失败";
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Location"
message:errorMsg
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OtherBtn",nil];
[alert show];
[alert release];
}
- (IBAction)StartLocation:(id)sender {
//初始化位置管理器
locManager = [[CLLocationManager alloc]init];
//设置代理
locManager.delegate = self;
//设置位置经度
locManager.desiredAccuracy = kCLLocationAccuracyBest;
//设置每隔100米更新位置
locManager.distanceFilter = 100;
//开始定位服务
[locManager startUpdatingLocation];
}