やあみんな、私はコンパスを使って所定の場所の方向を指すアプリを作ろうとしていますが、今のところ私は基本的なコンパスの作り方を理解しようとしています。ガイドに従いましたが、ヘッダーとして常に「-1」が表示され、一度だけ機能するようになりました。それ以降、コードを変更していません。どんなアイデアも役に立ちます。
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface TrackerViewController : UIViewController <CLLocationManagerDelegate> {
}
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) IBOutlet UISwitch *toggle;
@property (nonatomic, retain) IBOutlet UIImageView *compass;
@property (nonatomic, retain) IBOutlet UILabel *headingLabel;
-(IBAction)toggleSwitch;
@end
および実装ファイル...
#import "TrackerViewController.h"
@implementation TrackerViewController
@synthesize locationManager;
@synthesize toggle;
@synthesize compass;
@synthesize headingLabel;
- (IBAction)toggleSwitch {
if(self.toggle.isOn) {
[self.locationManager startUpdatingHeading];
} else {
[self.locationManager stopUpdatingHeading];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if ([CLLocationManager headingAvailable]) {
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;
} else {
[[[[UIAlertView alloc] initWithTitle:@"Aw snap!"
message:@"Device doesn't support heading updates"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease] show];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading
*)newHeading {
float heading = [newHeading trueHeading] * M_PI / 180.0;
self.compass.transform = CGAffineTransformMakeRotation(-heading);
self.headingLabel.text = [NSString stringWithFormat:@"%d°", (int)[newHeading trueHeading]];
NSLog(@"%d", (int)[newHeading trueHeading]);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
// NSLog(@"Error!");
if (error.code == kCLErrorDenied) {
[[[[UIAlertView alloc] initWithTitle:@"Aw snap!"
message:@"User didn't allow heading updates"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease] show];
self.toggle.on = NO;
[self.locationManager stopUpdatingHeading];
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
self.locationManager = nil;
self.compass = nil;
self.toggle = nil;
self.headingLabel = nil;
[super dealloc];
}
@end