2011-02-24 75 views
0

嘿,我正在嘗試構建一個應用程序,該應用程序將使用指南針指向預定位置的方向,但現在我正試圖瞭解如何製作基本指南針。我遵循了一個指南,但是我總是得到「-1」作爲標題,並且只能得到它的工作一次,而且我從未更改過代碼。任何想法都會有所幫助。CLLocation header始終是-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 
+0

我注意到,當「trueHeading」(在didUpdateHeading中)的每個引用更改爲「magneticHeading」時,它每次都有效。磁性更準確/不如真實準確? – 2011-02-24 04:02:44

回答

0

magneticHeading 在此屬性的值表示相對於磁北極,這是從地理北極不同的標題。值0表示設備指向磁北,90表示指向東,180指代指向南,依此類推。此屬性中的值應始終有效。