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];
}