iOS development manual Chinese version
/ IOS定位操作
IOS定位操作
IOS定位操作
簡(jiǎn)介
在IOS中通過(guò)CoreLocation定位,可以獲取到用戶(hù)當(dāng)前位置,同時(shí)能得到裝置移動(dòng)信息。
實(shí)例步驟
1、創(chuàng)建一個(gè)簡(jiǎn)單的View based application(視圖應(yīng)用程序)。
2、擇項(xiàng)目文件,然后選擇目標(biāo),然后添加CoreLocation.framework,如下所示
3、在ViewController.xib中添加兩個(gè)標(biāo)簽,創(chuàng)建ibOutlet名為latitudeLabel和longtitudeLabel的標(biāo)簽
4、現(xiàn)在通過(guò)選擇" File-> New -> File... -> "選擇Objective C class 并單擊下一步
5、把"sub class of"作為NSObject,將類(lèi)命名為L(zhǎng)ocationHandler
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、更新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,如下所示
#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
輸出
當(dāng)我們運(yùn)行該應(yīng)用程序,會(huì)得到如下的輸出: