您可以在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];
}
...
在你的控制器:
ViewController.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
...
}
看看[这篇文章](http://stackoverflow.com/a/13896966/593709) –
谢谢!有意义 –