解决此问题的一种常见方法是专门使用您的 AppDelegate 作为 CLLocationManager 委托。在 AppDelegate 的回调方法中,您可以检查在任何给定时间哪个 ViewController(如果有)处于活动状态,并根据需要从回调方法调用该 ViewController。
为此,您必须在 AppDelegate 上为每个使用 CoreLocation 服务的 ViewController 创建一个属性:
@interface MyAppDelegate : UIResponder <CLLocationManagerDelegate>
@property (strong, nonatomic) FirstViewController *firstViewController;
@property (strong, nonatomic) SecondViewController *secondViewController;
@end
然后在加载 ViewController 时设置相应的属性。像这样:
- (void)viewDidLoad
{
[super viewDidLoad];
MyAppDelegate *appDelegate = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
appDelegate.firstViewController = self;
...
}
完成此操作后,您可以在 MyAppDelegate 中专门注册回调,但将它们传递给单独的 ViewController,如下所示:
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
if (self.firstViewController != Nil) {
[self locationManager:manager didEnterRegion:region];
}
}