今回は、iOSのAPIを使用して現在位置を取得します。
今回の開発環境は以下の通りです。
・OS X v10.9.3
・Xcode v5.1.1
位置情報を取得するクラス CLLocationManager を使用します。
インスタンスメソッド startUpdatingLocation で位置情報の取得を開始します。
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
取得の開始後、呼び出されるデリゲートメソッドは下記の通りです。
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;
取得に成功したときに呼び出される。
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
取得に失敗したときに呼び出される。
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
self.latitude = newLocation.coordinate.latitude;
self.longitude = newLocation.coordinate.longitude;
[self.locationManager stopUpdatingLocation];
}
取得に成功したときは、CLLocation オブジェクトから、
現在位置の緯度(latitude)及び、経度(longitude)を取得することができます。
また、インスタンスメソッド stopUpdatingLocation で取得の停止を行います。
位置情報の取得を行うアプリを作成する際に注意事項があります。
それは、アプリをApp Storeに登録時の審査のガイドラインに記載されています。
App Store Review Guidelines
https://developer.apple.com/appstore/resources/approval/guidelines.html
4. Location
4.1 Apps that do not notify and obtain user consent before collecting, transmitting, or using location data will be rejected
位置情報を収集する前に通知しない、またはユーザーの同意を得ないまま送信、
使用するアプリはリジェクト対象となります。
したがって、位置情報を取得する場合は、
下記のような同意ポップアップ、または通知ポップアップを表示しましょう。
UIAlertView *alert = [[UIAlertView alloc] init];
alert.delegate = self;
alert.message = @"現在位置を取得しますか?";
[alert addButtonWithTitle:@"いいえ"];
[alert addButtonWithTitle:@"はい"];
[alert show];
以上です。