2014-04-01 98 views
0

我想獲取設備的當前位置。代碼正常工作正常。如果用戶未更改位置服務的應用程序授權狀態,則會給出位置。我也能夠檢查用戶是否拒絕了位置服務的許可。獲取當前位置的問題

問題是當用戶取消授權應用程序使用位置服務,然後再次授權。在這種情況下,在此之後,如果我試圖讓位置它給nil雖然它叫​​

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status 

委託方法與狀態3kCLAuthorizationStatusAuthorized

代碼獲取當前位置:

CLLocation * location = self.locationManager.location; 

getter方法:

- (CLLocationManager *)locationManager 
{ 
    if (!locationManager) 
    { 
     locationManager = [[CLLocationManager alloc] init]; 
     locationManager.delegate = self; 
    } 

    return locationManager; 
} 

CLLocationManager委託方法:

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status 
{ 
    DLog(@"Location authorization changed : %d", status); 

    // If user has denied permission for location service 
    if (status == kCLAuthorizationStatusDenied) 
    { 
     DLog(@"Location service denied."); 

     // If authorization status changed method is already called, then SDK will not call again on same object. 
     // Thus, set CLLocationManager object to nil so that next time we try to get location, it will create a new object, 
     // and that will send message about authorization status changed. 
     self.locationManager.delegate = nil; 
     self.locationManager = nil; 
    } 
    else if (status == kCLAuthorizationStatusNotDetermined) 
    { 
     // If authorization status changed method is already called, then SDK will not call again on same object. 
     // Thus, set CLLocationManager object to nil so that next time we try to get location, it will create a new object, 
     // and that will send message about authorization status changed. 
     self.locationManager.delegate = nil; 
     self.locationManager = nil; 
    } 
    else if (status == kCLAuthorizationStatusAuthorized) 
    { 

    } 
} 

對此有何想法?

+0

在上面你將locationManager.delegate設置爲nil,如果授權被撤銷......你是否曾經將它重新設置爲適當的類? – Volker

+1

只是注意到你還將locationManager設置爲零... – Volker

+1

根據您在代碼中的意見,您可以在某處重新創建'locationManager'對象 - 您確定在設置'self.locationServiceDisabled = false'時觸發了這個對象嗎? – Paulw11

回答

0

self.locationManager.locationnil因爲您從未開始更新位置。

在蘋果文檔中指出有關的LocationManager的location屬性:

此屬性的值是零,如果沒有位置的數據已經去過檢索 。

因此,您需要以某種方式更新您的iPhone位置!

Apple Docs CLLocationManager

通常,這意味着你要調用

[self.locationManager startUpdatingLocation]

,但你也可以使用

[self.locationManager startMonitoringSignificantLocationChanges]

+0

我希望你在這裏添加你評論的全文。這會讓這個答案好多了。謝謝。 – Geek

0

如果委託設爲零,你將得不到關於授權狀態更新的更新,不是嗎?

self.locationManager.delegate = nil; 

,我認爲你應該保持的委託,以獲得授權狀態更新,然後調用startUpdatingLocation方法,以獲得當前位置。

- (void)startUpdatingLocation 
+0

如果您關心仔細查看我的代碼,那麼請清楚,在getter方法中,我再次設置委託。 – Geek