3

您如何设置AppDelegate和 aViewController作为模型核心定位类的侦听器?什么是正确的设计选择?

我对有一个模型类来实现CoreLocation和位置更新很感兴趣。我猜这个类应该是 a sharedSingleton,因为我AppDelegate和我都ViewController希望访问它。

当我viewController调用它时,我想要CLLocationManager使用startUpdatingLocation.

当应用程序进入后台时,我想使用 startMonitoringSignificantLocationChanges 监视 AppDelegate 中的位置更新。

我的问题是,如何设置模型类来处理这些不同类型的位置更新,以及通知 ViewController 或 AppDelegate 找到新位置?使用NSNotification? 委派似乎不起作用,因为它是一对一的关系。

感谢您帮助弄清楚如何设计它。

谢谢!

4

1 回答 1

6

您可以在 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
   ...
}
于 2012-12-26T09:36:48.930 回答