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

Roh*_*wal 3 iphone objective-c core-location nsnotificationcenter ios

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

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

当我viewController打电话给它时,我想要CLLocationManager使用它startUpdatingLocation.

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

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

感谢您在确定如何设计时的帮助.

谢谢!

Lud*_*uda 9

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

AppDelegate.h

@interface AppDelegate : NSObject <UIApplicationDelegate,CLLocationManagerDelegate...> {
    ...
    CLLocationManager* locationManager;
    CLLocationCoordinate2D myLocation;
    ...
}
@property(nonatomic) CLLocationCoordinate2D myLocation;
...
@end
Run Code Online (Sandbox Code Playgroud)

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];   
}

...
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

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
   ...
}
Run Code Online (Sandbox Code Playgroud)