做自(zì)由與創造的先行者

iOS定位操作(zuò)

iOS開(kāi)發手冊

IOS定位操作(zuò)

簡介

在IOS中通過CoreLocation定位,可以獲取到(dào)用(yòng)戶當前位置,同時(shí)能(néng)得到(dào)裝置移動信息。

實例步驟

1、創建一個簡單的View based application(視(shì)圖應用(yòng)程序)。

2、擇項目文(wén)件,然後選擇目标,然後添加CoreLocation.framework

3、在ViewController.xib中添加兩個标簽,創建ibOutlet名爲latitudeLabel和(hé)longtitudeLabel的标簽

4、現(xiàn)在通過選擇" File-> New -> File... -> "選擇Objective C class 并單擊下(xià)一步

5、把"sub class of"作(zuò)爲NSObject,将類命名爲LocationHandler

6、選擇創建

7、更新LocationHandler.h,如下(xià)所示

#import

#import

@protocol LocationHandlerDelegate

@required

-(void) didUpdateToLocation:(CLLocation*)newLocation

fromLocation:(CLLocation*)oldLocation;

@end

@interface LocationHandler : NSObject

{

CLLocationManager *locationManager;

}

@property(nonatomic,strong) id delegate;

+(id)getSharedInstance;

-(void)startUpdating;

-(void) stopUpdating;

@end

8、更新LocationHandler.m,如下(xià)所示

#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,如下(xià)所示

#import

#import "LocationHandler.h"

@interface ViewController : UIViewController

{

IBOutlet UILabel *latitudeLabel;

IBOutlet UILabel *longitudeLabel;

}

@end

10、更新ViewController.m,如下(xià)所示

#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

網站(zhàn)建設開(kāi)發|APP設計(jì)開(kāi)發|小(xiǎo)程序建設開(kāi)發
下(xià)一篇:iOS整合iAD
上(shàng)一篇:iOS GameKit