2012-05-24 74 views
5

目前,開發一個需要從CLLocationManager獲取最後位置的應用程序(沒有任何定期跟蹤)。不管多大,準確是多少。我不需要也不想開始跟蹤 - 我只需要從緩存中獲取最後一個位置,就是這樣。恕我直言,CLLocationManager是iOS中的共享組件,如果某些應用程序使用位置跟蹤,則另一個應用程序應該能夠使用CLLocationManager.location中最新的位置。只需分配/初始化CLLocationManager並獲取其位置即可。但事實並非如此。我在iPhone4上測試過 - 啓動谷歌地圖,看到我當前的位置,然後去我的應用程序,但[[CLLocationManager alloc] init]位置屬性爲零後。應用程序是否應該啓動位置跟蹤,以便從CLLocationManager獲取任何最後一個已知位置?

更新:嘗試[locationManager startUpdatingLocation];和[locationManager stopUpdatingLocation];但結果是一樣的。我想,唯一的解決辦法是開始定期跟蹤?

UPDATE2:奇怪,但在CLLocationManager的alloc/init之後沒有提示「應用程序想使用位置服務」。這裏是我的代碼片段:

CLLocationManager *locationManager = [[CLLocationManager alloc] init]; 

[locationManager startUpdatingLocation]; 
[locationManager stopUpdatingLocation]; 
NSLog(@"%@", locationManager.location); //prints nil 
+0

我建議你看看[如何找到您的當前位置與CoreLocation(http://stackoverflow.com/questions/6516967/how-to-find- your-current-location-with-corelocation),並將找到的位置存儲在「NSArray」中。 –

回答

2

首先,你應該檢查你的locationManager有一個,讓我們說,「靜」的位置預先保存。

如果是這樣,就完成了。

如果不是,你應該startUpdatingLocation,然後,在didUpdateToLocation:fromLocation:回調,stopUpdatingLocation一旦你獲得的位置。

我的經驗表明,這是獲得唯一位置的最佳方法。

更新,以匹配作者更新:

你不應該stopUpdatingLocationstartUpdatingLocation之後。 startUpdatingLocation在後臺啓動一項服務,因此您應該等到您獲得一個位置,然後在回調方法中調用它。

+0

你是什麼意思'靜態'位置?如果我去谷歌地圖,並能夠看到我目前的位置,那麼應該被視爲靜態位置?谷歌地圖肯定會使用位置服務,因此在CLLocationManager中至少應該有一個靜態位置。 – Centurion

+0

我的意思是沒有通過'didUpdateToLocation:fromLocation:'回調獲得你的應用程序的位置。是的,Google地圖使用位置服務,但不能保證您的應用可以獲取其他應用獲得的位置。 – sonxurxo

+1

順便說一句,我99%確定當你使用** locationManager啓動**時,應該會出現警報,而不是在你分配和初始化它時。 – sonxurxo

1

若要使用CLLocationManager,您需要在某處實施CLLocationManagerDelegate

-[CLLocationManager startUpdatingLocation]開始一個異步過程。如果您在同一個runloop循環中停止它,則該進程永遠不會啓動,這就是您永遠不會看到權限對話框的原因。

它是這樣的:

@interface MyClass : NSObject <CLLocationManagerDelegate> { 
    CLLocationManager *manager; 
    CLLocation *lastLocation; 
} 

@end 

@implementation 

- (id)init { 
    self = [super init]; 
    if (self) { 
     manager = [[CLLocationManager alloc] init]; 
     manager.delegate = self; 
     [manager startUpdatingLocation]; 
    } 
    return self; 
} 

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation; 
{ 
    lastLocation = newLocation; 
    [manager stopUpdatingLocation]; 
} 

// in your real implementation be sure to handle the error cases as well. 
@end 
相關問題