在 iOS 系統(tǒng)中,我們可以很容易地找到用戶的當(dāng)前位置,用戶允許應(yīng)用程序訪問的核心位置框架的幫助信息。
涉及的步驟
1. 創(chuàng)建一個(gè)簡(jiǎn)單的 View based application.
2. 選擇項(xiàng)目文件,然后選擇目標(biāo),然后添加如下所示 CoreLocation.framework。
3. 添加兩個(gè)標(biāo)簽在ViewController.xib并創(chuàng)建 ibOutlets 命名標(biāo)簽分別為 latitudeLabel 和 longitudeLabel。
4. 現(xiàn)在創(chuàng)建一個(gè)新的文件,通過選擇 File-> New -> File... -> select Objective-C類并點(diǎn)擊 next
5. 命名類為 LocationHandler ,并設(shè)置為 NSObject 的子類.
6. 選擇創(chuàng)建
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. 現(xiàn)在更新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 我們實(shí)現(xiàn)了 LocationHandler 委托并創(chuàng)建兩個(gè) 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:(上一篇:iOS - 應(yīng)用程序內(nèi)購(gòu)買下一篇:iOS - Toolbar(工具欄)