3

モデルのコアロケーションクラスのリスナーとなるようにAppDelegateとをどのように設定しますか?ViewController適切な設計の選択は何ですか?

CoreLocation実装するモデルクラスと場所の更新に興味があります。私とこのクラスのsharedSingleton両方がアクセスしたいので、このクラスはである必要があるAppDelegateと思います。ViewController

viewControllerがそれを呼ぶとき、私はそれCLLocationManagerを使いたいですstartUpdatingLocation

アプリがバックグラウンドに移行したときに、startMonitoringSignificantLocationChangesを使用してAppDelegateで位置の更新を監視したいと思います。

私の質問は、これらのさまざまなタイプの場所の更新を処理し、新しい場所が見つかったことをViewControllerまたはAppDelegateに通知するようにモデルクラスを設定するにはどうすればよいですか?NSNotification?を使用する 委任は1対1の関係であるため、機能していないようです。

これを設計する方法を理解する上であなたの助けに感謝します。

ありがとう!

4

1 に答える 1

6

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
   ...
}
于 2012-12-26T09:36:48.930 に答える