過年后第一次來上班,那么我們來說說iOS上的定位服務首先說定位共分三種方法,第一利用WiFi,第二是移動蜂窩網絡,第三是利用GPS然后是iPod touch上是不具備GPS模塊的,所以不能利用GPS進行定位最后想說的是,因為老板不相信iPhone可以利用GPS,所以下面的例子可以在關閉WiFi,并且拔出sim卡的情況下,進行測試的,親測有效開始第一步,導入框架 CoreLocation第二步,引入框架并設置相應的協議,設置好變量#import#import#import@interface MeViewController : UIViewController{
UIButton *button;
//位置相關
CLLocationManager *location;
}
@end
第三步,初始化 location
//定位服務
location = [[CLLocationManager alloc] init]; //初始化
location.delegate = self; //設置代理
location.desiredAccuracy = kCLLocationAccuracyBest; //設置精度
location.distanceFilter = 1000.0f; //表示至少移動1000米才通知委托更新
[location startUpdatingLocation]; //開始定位服務
第四步,實現委托代碼,獲取位置后彈出信息
//定位信息
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
float lat = currLocation.coordinate.latitude;? //正值代表北緯
float lon = currLocation.coordinate.longitude; //正值代表東經
if (lat != 0 && lon != 0)
{
NSString *string = [NSString stringWithFormat:@"您的當前位置為%f,%f",lat,lon];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"位置信息" message:string delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"確認", nil];
[alert show];
}
}
第五步,出于責任心,在離開該頁面之后要關閉定位服務
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[location stopUpdatingLocation];
}