如何将AppDelegate
和ViewController
设置为模型重定位类的侦听器?什么是正确的设计选择??
我对使用模型类实现CoreLocation
和位置更新感兴趣。我猜这个课程应该是sharedSingleton
,因为我的AppDelegate
和ViewController
都希望能够访问它。
当我viewController
调用它时,我希望CLLocationManager
使用startUpdatingLocation
。
当应用程序进入后台时,我想使用startMonitoringSignificantLocationChanges监控AppDelegate中的位置更新。
我的问题是,如何设置模型类来处理这些不同类型的位置更新,以及通知ViewController或AppDelegate是否找到了新位置?使用NSNotification
?代表团似乎没有成功,因为它是一对一的关系。
感谢您帮助弄清楚如何设计它。
谢谢!
答案 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
...
}