「Objective-C」iOS開発で位置情報を取得するサンプルコード

1.blockの宣言、定義
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@interface GpsManager : NSObject <CLLocationManagerDelegate> {
CLLocationManager *manager;
void (^saveGpsCallback) (double lat, double lng);
}
+ (void) getGps:( void (^)(double lat, double lng) )cb;
+ (void) stop;

@end

2.GpsManagerの定義
#import “GpsManager.h"
#import <CoreLocation/CoreLocation.h>
#import <UIKit/UIKit.h>

@implementation GpsManager

+ (id) sharedGpsManager {
static id s;
if (s == nil) {
s = [[GpsManager alloc] init];
}
return s;
}
– (id)init {
self = [super init];
if (self) {
manager = [[CLLocationManager alloc] init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;

//iOS8.0を互換
/* Info.plistに2つ項目を追加
NSLocationAlwaysUsageDescription Boolean YES
NSLocationWhenInUseUsageDescription Boolean YES
*/

if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
}

float osVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (osVersion >= 8) {
[manager requestWhenInUseAuthorization];
[manager requestAlwaysAuthorization];
}
}
return self;
}
– (void) getGps:( void (^)(double lat, double lng) )cb {
if ([CLLocationManager locationServicesEnabled] == FALSE) {
return;
}
// copyメソッド
saveGpsCallback = [cb copy];
[manager stopUpdatingLocation];
// 新しいデータ位置
[manager startUpdatingLocation];
}

+ (void) getGps:( void (^)(double lat, double lng) )cb {
[[GpsManager sharedGpsManager] getGps:cb];
}

– (void) stop {
[manager stopUpdatingLocation];
}
+ (void) stop {
[[GpsManager sharedGpsManager] stop];
}

– (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
for (CLLocation *loc in locations) {
CLLocationCoordinate2D l = loc.coordinate;
double lat = l.latitude;
double lnt = l.longitude;

//blocksを利用
if (saveGpsCallback) {
saveGpsCallback(lat, lnt);
}
}
}

3.getGpsの処理
__block BOOL isOnece = YES;
[GpsManager getGps:^(double lat, double lng) {
isOnece = NO;

NSLog(@"lat lng (%f, %f)", lat, lng);

if (!isOnece) {
[GpsManager stop];
}
}];

[GpsManager getGps:^(double lat, double lng) {

NSLog(@"lat lng (%f, %f)", lat, lng);
}];

IOS

Posted by arkgame