我正在尝试编写一个简单的地理定位应用程序来查找用户在 iOS 中的位置。当用户按下按钮时,会找到并显示用户的位置,并且应该在触发 startUpdatingLocation 时发生变化。但是 startUpdatingLocation 没有被解雇。这是我的代码:
在我的 ViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface CGViewController : UIViewController<CLLocationManagerDelegate>
@property (strong, nonatomic) IBOutlet UITextField *nameField;
- (IBAction)butStart:(id)sender;
@property (strong, nonatomic) IBOutlet MKMapView *map;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) IBOutlet UILabel *latitude;
@property (strong, nonatomic) IBOutlet UILabel *longitude;
@property (strong, nonatomic) IBOutlet UILabel *altitude;
@end
在我的 ViewController.m 中:
- (IBAction)butStart:(id)sender {
self.locationManager=[[CLLocationManager alloc] init];
if([CLLocationManager locationServicesEnabled]){
self.locationManager.delegate=self;
self.locationManager.distanceFilter=1;
[self.locationManager startUpdatingLocation];
}
}
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog( @"new location = %@", [newLocation description] );
MKCoordinateSpan span;
span.latitudeDelta = 0.2;
span.longitudeDelta = 0.2;
MKCoordinateRegion region;
region.span = span;
region.center = newLocation.coordinate;
map.showsUserLocation = YES;
self.latitude.text = [NSString stringWithFormat:@"%.3f", newLocation.coordinate.latitude];
self.longitude.text = [NSString stringWithFormat:@"%.3f", newLocation.coordinate.longitude];
}
我试图省略不必要的代码,比如我拥有的地图。我见过的每个示例都在 AppDelegate.h/.m 中设置了 locationManager 内容,而我试图在用户按下按钮时调用它。我不确定为什么它没有被调用。