2015-05-26 62 views
1

您可以查看下面的代碼,它嘗試使用代理嘗試locationManager,並嘗試返回設備的當前位置。Objective C locationManager無法獲取當前位置,總是返回0

但總是返回0(允許位置的權限)

.M

self.locationManager = [[CLLocationManager alloc] init]; 
self.locationManager.delegate = self; 
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
self.locationManager.distanceFilter = kCLDistanceFilterNone; 
[self.locationManager startUpdatingLocation]; 

if(IS_OS_8_OR_LATER) { 
    [self.locationManager requestAlwaysAuthorization]; 
} 


CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; 

if (status == kCLAuthorizationStatusAuthorizedAlways) { 
    // TODO: Handle status authorized always 


} else if (status == kCLAuthorizationStatusNotDetermined) { 
    // TODO: Handle status not determined 


} else { 
    // TODO: Handle other 
} 






- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { 

    //NSLog(@"newLocation: %@", newLocation); 

} 

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ 

    //NSLog(@"Error: %@",[error description]); 

} 

的info.plist

<key>NSLocationAlwaysUsageDescription</key> 
<string>We would like to use your location.</string> 
<key>NSLocationWhenInUseUsageDescription</key> 
<string>We would like to use your location.</string> 
+0

您是否有很強的參考您的locationManager? – Groot

+0

是@property(強,非原子)CLLocationManager * locationManager; 在.h上聲明 –

+0

你是指什麼意思返回0? – tounaobun

回答

0

請儘量requestAlwaysAuthorization之後調用startUpdatingLocation。並使用下面的didUpdateLocations委託方法。

if(IS_OS_8_OR_LATER) { 
    [self.locationManager requestAlwaysAuthorization]; 
} 

[self.locationManager startUpdatingLocation]; 


- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 

     _currentLocation = [locations objectAtIndex:0]; 
     //do your stuff with the location 

    } 

對於模擬器測試 - 選擇仿真和調試轉到 - >位置 - >蘋果或市潤

用於器件測試請用地圖查看你是否得到當前位置或沒有。有時設備由於房屋內部而不能獲得當前位置。