iOS - 位置处理


只要用户允许应用程序在核心位置框架的帮助下访问该信息,我们就可以轻松地在 iOS 中定位用户的当前位置。

位置处理 - 涉及的步骤

步骤 1 - 创建一个简单的基于视图的应用程序。

步骤 2 - 选择您的项目文件,然后选择目标,然后添加 CoreLocation.framework,如下所示 -

iOS教程

步骤 3 - 在ViewController.xib中添加两个标签并创建 ibOutlet,分别将标签命名为latitudeLabellongitudeLabel

步骤 4 - 通过选择文件 → 新建 → 文件... → 选择Objective 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 委托并创建两个 ibOutlet -

#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

输出

当我们运行该应用程序时,我们将得到以下输出 -

iOS教程