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

3
请问如何设置AppDelegateViewController作为模型corelocation类的监听器?有哪些合适的设计选择?
我想要一个实现CoreLocation和位置更新的模型类。这个类应该是sharedSingleton,因为我的AppDelegateViewController都希望访问它。
当我的viewController调用它时,我希望CLLocationManager使用startUpdatingLocation
当应用程序进入后台时,我希望在AppDelegate中使用startMonitoringSignificantLocationChanges监视位置更新。
我的问题是,如何设置模型类来处理这些不同类型的位置更新,并通知ViewController或AppDelegate找到了新位置?使用NSNotification吗?委托似乎行不通,因为它是一对一关系。
感谢您的帮助,解决如何设计这个问题。
谢谢!

1
请查看此帖子 - Adil Soomro
1个回答

6

你可以在AppDelegate中使用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
   ...
}

这一切都有道理,但我如何区分我的应用程序是在后台还是在前台?当我在后台时,我想使用significantLocationChange而不通知我的视图控制器。 - Rohan Agarwal
嗨,Rohan,我已更新我的答案以处理背景和前景。请查看两个类中的更新。 - Luda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接