Операции с местоположением в iOS


Введение

В iOS определение местоположения через CoreLocation позволяет получить текущее местоположение пользователя, а также информацию о перемещении устройства.

Шаги примера

1. Создайте простое приложение на основе представления (view application).

2. Выберите файл проекта, затем выберите цель, а затем добавьте CoreLocation.framework, как показано ниже.

CoreLocation_Library_Addition

3. Добавьте две метки в ViewController.xib, создайте метки с именами IBOutlet latitudeLabel и longitudeLabel.

4. Теперь, выбрав " File-> New -> File... -> ", выберите "Objective C class" и нажмите Next.

5. Укажите в поле "sub class of" значение NSObject и назовите класс LocationHandler.

6. Выберите Create.

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

Вывод

Когда мы запустим приложение, мы получим следующий вывод:

locationOutput

Другие расширения