iOS将ViewController和AppDelegate设置为CoreLocation模型类的侦听器

时间:2012-12-26 07:25:56

标签: iphone objective-c ios core-location nsnotificationcenter

如何将AppDelegateViewController设置为模型重定位类的侦听器?什么是正确的设计选择??

我对使用模型类实现CoreLocation和位置更新感兴趣。我猜这个课程应该是sharedSingleton,因为我的AppDelegateViewController都希望能够访问它。

当我viewController调用它时,我希望CLLocationManager使用startUpdatingLocation

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

我的问题是,如何设置模型类来处理这些不同类型的位置更新,以及通知ViewController或AppDelegate是否找到了新位置?使用NSNotification?代表团似乎没有成功,因为它是一对一的关系。

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

谢谢!

1 个答案:

答案 0 :(得分:9)

您可以在AppDelagete中安装locationManager。并让app委托为您处理所有应用程序的位置更新。

<强> 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
   ...
}