在任何视图中按下导航栏中的 locateButton 后,我想在所有视图中更新用户位置。我从创建一个单例开始。
位置.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface Location : NSObject <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager* locationManager;
+ (Location*)sharedSingleton;
@end
位置.m
#import "Location.h"
@implementation Location {
CLLocationManager *locationManager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
}
@synthesize locationManager;
- (id)init {
self = [super init];
if(self) {
self.locationManager = [CLLocationManager new];
[self.locationManager setDelegate:self];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setHeadingFilter:kCLHeadingFilterNone];
[self.locationManager startUpdatingLocation];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//do any more customization to your location manager
}
return self;
}
+ (Location*)sharedSingleton {
static Location* sharedSingleton;
if(!sharedSingleton) {
@synchronized(sharedSingleton) {
sharedSingleton = [Location new];
}
}
return sharedSingleton;
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
latLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
longLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
// Stop Location Manager
[locationManager stopUpdatingLocation];
// Reverse Geocoding
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
addressLabel.text = [NSString stringWithFormat:@"%@, %@",
placemark.locality,
placemark.administrativeArea];
addressLabel.numberOfLines = 0;
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
@end
当在当前视图中按下顶部导航栏中的 locationButton 时,我想使用它来更新每个视图上的用户纬度和经度。
- (IBAction)locationPressed:(id)sender {
[[Location sharedSingleton].locationManager startUpdatingLocation];
}
NSNotifications 会是最好的吗?如果是这样,我将如何在 Location.m 和视图控制器中实现它们?谢谢。