過年後第一次來上班,那麼我們來說說iOS上的定位服務
首先說定位共分三種方法,第一利用WiFi,第二是移動蜂窩網絡,第三是利用GPS
然後是iPod touch上是不具備GPS子產品的,是以不能利用GPS進行定位
最後想說的是,因為老闆不相信iPhone可以利用GPS,是以下面的例子可以在關閉WiFi,并且拔出sim卡的情況下,進行測試的,親測有效
開始
第一步,導入架構 CoreLocation
第二步,引入架構并設定相應的協定,設定好變量
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
@interface MeViewController : UIViewController<CLLocationManagerDelegate>
{
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];
}