iOS - 位置處理


簡介

iOS 系統中,我們可以很容易地找到使用者的當前位置,使用者允許應用程式存取的核心位置框架的幫助資訊。

 

涉及的步驟

1. 建立一個簡單的 View based application.

2. 選擇專案檔案,然後選擇目標,然後新增如下所示 CoreLocation.framework。

iOS Tutorial

3. 新增兩個標籤在ViewController.xib並建立 ibOutlets 命名標籤分別為 latitudeLabel 和 longitudeLabel。

4. 現在建立一個新的檔案,通過選擇 File-> New -> File... -> select Objective-C類並點選 next

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 委託並建立兩個 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:(CLLocation *)oldLocation{
    [latitudeLabel setText:[NSString stringWithFormat:
    @"Latitude: %f",newLocation.coordinate.latitude]];
    [longitudeLabel setText:[NSString stringWithFormat:
    @"Longitude: %f",newLocation.coordinate.longitude]];

}

@end

輸出

現在,當我們執行程式時,我們會得到下面的輸出。

iOS Tutorial