您可以在 AppDelagete 中拥有 locationManager。并让应用程序委托为您处理所有应用程序的位置更新。
AppDelegate.h
@interface AppDelegate : NSObject <UIApplicationDelegate,CLLocationManagerDelegate...> {
...
CLLocationManager* locationManager;
CLLocationCoordinate2D myLocation;
...
}
@property(nonatomic) CLLocationCoordinate2D myLocation;
...
@end
AppDelegate.m
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
...
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
[locationManager startUpdatingLocation];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[locationManager startMonitoringSignificantLocationChanges];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
myLocation = newLocation.coordinate;
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateControlersThatNeedThisInfo" object:nil userInfo:nil];
}
...
在您的控制器中:
视图控制器.m
...
- (void)viewDidAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourFunction) name:@"updateControlersThatNeedThisInfo" object:nil];
}
-(void)yourFunction{
AppDelegate *app = [[UIApplication sharedApplication] delegate];
CLLocation myLocation = app.myLocation;
if(app.applicationState == UIApplicationStateBackground)
//background code
else
//foreground code
...
}