2015-05-26 63 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 

    } 

对于模拟器测试 - 选择仿真和调试转到 - >位置 - >苹果或市润

用于器件测试请用地图查看你是否得到当前位置或没有。有时设备由于房屋内部而不能获得当前位置。