我们可以轻松找到用户在iOS中的当前位置,前提是用户允许应用程序在核心位置框架的帮助下访问信息.
第1步 : 创建一个简单的基于视图的应用程序.
第2步 : 选择你的项目文件,然后选择目标,然后添加CoreLocation.framework,如下图所示 :
第3步 : 在 ViewController.xib 中添加两个标签,并创建ibOutlets,分别将标签命名为 latitudeLabel 和 longitudeLabel .
第4步 : 选择File&rarr创建一个新文件;新的 → 档案... → 选择目标C类并单击下一步.
步骤5 : 将该类命名为 LocationHandler ,并将" 的子类命名为NSObject.
步骤6 : ;选择创建.
步骤7 : 更新 LocationHandler.h ,如下 :
#import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @protocol LocationHandlerDelegate <NSObject> @required -(void) didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation; @end @interface LocationHandler : NSObject<CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property(nonatomic,strong) id<LocationHandlerDelegate> delegate; +(id)getSharedInstance; -(void)startUpdating; -(void) stopUpdating; @end
第8步 : 更新 LocationHandler.m ,如下 :
#import "LocationHandler.h" static LocationHandler *DefaultManager = nil; @interface LocationHandler() -(void)initiate; @end @implementation LocationHandler +(id)getSharedInstance{ if (!DefaultManager) { DefaultManager = [[self allocWithZone:NULL]init]; [DefaultManager initiate]; } return DefaultManager; } -(void)initiate { locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; } -(void)startUpdating{ [locationManager startUpdatingLocation]; } -(void) stopUpdating { [locationManager stopUpdatingLocation]; } -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if ([self.delegate respondsToSelector:@selector (didUpdateToLocation:fromLocation:)]) { [self.delegate didUpdateToLocation:oldLocation fromLocation:newLocation]; } } @end
第9步 : 更新 ViewController.h ,如下所示我们已经实现了 LocationHandler委托并创建了两个ibOutlets :
#import <UIKit/UIKit.h> #import "LocationHandler.h" @interface ViewController : UIViewController<LocationHandlerDelegate> { IBOutlet UILabel *latitudeLabel; IBOutlet UILabel *longitudeLabel; } @end
第10步 : 更新 ViewController.m 如下 :
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[LocationHandler getSharedInstance]setDelegate:self]; [[LocationHandler getSharedInstance]startUpdating]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [latitudeLabel setText:[NSString stringWithFormat: @"Latitude: %f",newLocation.coordinate.latitude]]; [longitudeLabel setText:[NSString stringWithFormat: @"Longitude: %f",newLocation.coordinate.longitude]]; } @end
当我们运行应用程序时,我们会得到以下输出 :