2

我正在使用CoreLocation,並從我的應用程序AppDelegate中啓動locationManager。示例代碼如下...從其他ViewController的locationManager方法訪問newLocation

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // ... 

    // start location manager 
    if([CLLocationManager locationServicesEnabled]) 
    { 
     myLocationManager_ = [[CLLocationManager alloc] init]; 
     myLocationManager_.delegate = self; 
     [myLocationManager_ startUpdatingLocation]; 
    } 
    else 
    { 
     // ... rest of code snipped to keep this short 

而且在這個方法中,我們看到更新後的位置。

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    NSString *currentLatitude = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude]; 
    NSLog(@"AppDelegate says: latitude: %@", currentLatitude); 

    // ... rest of code snipped 

現在,我的應用程序的其他領域內,我需要確定用戶當前位置(經度,緯度)。我可以將上面的代碼合併到需要當前位置的ViewControllers中,但是接下來我會運行多個CLLocationManager實例(我認爲) - 以及爲什麼複製此代碼?沒有一種方法可以從其他ViewControllers中獲取AppDelegate的位置信息嗎?

PS - 我使用的Xcode4.3瓦特/ ARC

回答

2

要做到這一點,聲明變量在你的appDelegate一個屬性:在您的m

@property (nonatomic, retain) NSArray *array;

(@synthesize太)

然後在您的視圖控制器,創建的appDelegate變量:

AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];

那麼你可以做: NSLog(@"%@", appDelegate.array);

+0

啊,多美的東西。謝謝! – ElasticThoughts 2012-03-09 19:02:10

6

謝謝mohabitar回答這對我來說!爲了清楚起見,我已經發布了我的代碼供其他人使用。

注意:只有下面顯示的相關部分。

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate> 

@property (strong, nonatomic) UIWindow *window; 

@property (nonatomic, strong) CLLocationManager *myLocationManager; 
@property (nonatomic, strong) CLLocation *currentLocation; 

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

    if([CLLocationManager locationServicesEnabled]) 
    { 
     currentLocation_ = [[CLLocation alloc] init]; 

     myLocationManager_ = [[CLLocationManager alloc] init]; 
     myLocationManager_.delegate = self; 
     [myLocationManager_ startUpdatingLocation]; 
    } 
} 

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 
    currentLocation_ = newLocation; 
} 

其他ViewControllers.h

@property (strong, nonatomic) CLLocation *currentLocation; 

其他ViewControllers.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    if([CLLocationManager locationServicesEnabled]) 
    { 
     AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate]; 
     currentLocation_ = [[CLLocation alloc] initWithLatitude:appDelegate.currentLocation.coordinate.latitude longitude:appDelegate.currentLocation.coordinate.longitude]; 
    } 
} 

再次感謝!

+0

很好的解決方案,工作正常! – TharakaNirmana 2015-09-01 07:06:09

相關問題