#import "LocationEx.h"
//LocationExの実装
@implementation LocationEx
//アラートの表示
- (void)showAlert:(NSString*)title text:(NSString*)text {
UIAlertView* alert=[[[UIAlertView alloc]
initWithTitle:title message:text delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
//ラベルのリサイズ
- (void)resizeLabel:(UILabel*)label {
CGRect frame=label.frame;
frame.size=[label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(512,512)
lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:frame];
}
//ラベルの生成
- (UILabel*)makeLabel:(CGPoint)pos
text:(NSString*)text font:(UIFont*)font {
UILabel* label=[[[UILabel alloc] init] autorelease];
[label setText:text];
[label setFont:font];
[label setTextColor:[UIColor blackColor]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextAlignment:UITextAlignmentLeft];
[label setNumberOfLines:0];
[label setLineBreakMode:UILineBreakModeWordWrap];
[self resizeLabel:label];
return label;
}
//初期化
- (void)viewDidLoad {
[super viewDidLoad];
//ラベルの生成
_label=[[self makeLabel:CGPointMake(0,0)
text:@"LocationEx"
font:[UIFont systemFontOfSize:16]] retain];
[self.view addSubview:_label];
//情報
_latitude =0.0f;
_longitude=0.0f;
_heading =0.0f;
//ロケーションマネージャーの生成
_locationManager=[[CLLocationManager alloc] init];
_locationManager.delegate=self;
//位置情報通知の開始
if ([_locationManager locationServicesEnabled]) {
[_locationManager startUpdatingLocation];
}
//方位情報通知の開始
if ([_locationManager headingAvailable]) {
[_locationManager startUpdatingHeading];
}
//タイマーの生成
[NSTimer scheduledTimerWithTimeInterval:0.1f
target:self
selector:@selector(onTick:)
userInfo:nil
repeats:YES];
}
//メモリ解放
- (void)dealloc {
//位置情報通知の停止
[_locationManager stopUpdatingLocation];
//方位情報通知の停止
[_locationManager stopUpdatingHeading];
//メモリ解放
[_label release];
_locationManager.delegate=nil;
[_locationManager release];
[super dealloc];
}
//定期処理
- (void)onTick:(NSTimer*)timer {
//ラベルの更新
NSMutableString* str=[NSMutableString string];
[str appendString:@"LocationEx\n"];
[str appendFormat:@"緯度:%+f\n",_latitude];
[str appendFormat:@"経度:%+f\n",_longitude];
[str appendFormat:@"方位:%+3.2f\n",_heading];
[_label setText:str];
[self resizeLabel:_label];
}
//位置情報更新時に呼ばれる
- (void)locationManager:(CLLocationManager*)manager
didUpdateToLocation:(CLLocation*)newLocation
fromLocation:(CLLocation*)oldLocation {
//緯度・経度の取得
CLLocationCoordinate2D coordinate=newLocation.coordinate;
_latitude =coordinate.latitude;
_longitude=coordinate.longitude;
}
//位置情報取得失敗時に呼ばれる
- (void)locationManager:(CLLocationManager*)manager
didFailWithError:(NSError*)error {
if ([error code]==kCLErrorDenied) {
[self showAlert:@"" text:@"位置情報取得は許可されていません"];
} else {
[self showAlert:@"" text:@"位置情報取得に失敗しました"];
}
}
//方位情報更新時に呼ばれる
- (void)locationManager:(CLLocationManager*)manager
didUpdateHeading:(CLHeading*)newHeading {
//方位の取得
_heading=newHeading.trueHeading;
}
//画面を端末の向きにあわせて回転
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)orientation {
return YES;
}
@end
|