2012-12-26 34 views
3

如何设置AppDelegateViewController作为模型corelocation类的侦听器?什么是适当的设计选择?iOS将ViewController和AppDelegate设置为CoreLocation模型类的侦听器

我很想让模型类实现CoreLocation和位置更新。我猜这个班级应该是sharedSingleton,因为我的AppDelegateViewController希望访问它。

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

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

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

感谢您了解如何进行设计的帮助。

谢谢!

+1

看看[这篇文章](http://stackoverflow.com/a/13896966/593709) –

+0

谢谢!有意义 –

回答

9

您可以在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 
    ... 
} 
+0

这一切都很有意义,但是如何区分我的应用程序在后台,以及何时我的应用程序位于前台?当我在后台,我想使用significantLocationChange并不通知我的视图控制器 –

+0

嗨Rohan,我已经更新了我的答案来处理背景和前景。请参阅两个课程的更新。 – Luda

+0

谢谢!这工作真的很好 –

相关问题