我试着获得我所在位置的坐标。
我堆栈溢出,所以我编码的内容如下:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
self.longitude=coordinate.longitude;
self.latitude=coordinate.latitude;
NSLog(@"dLongitude : %f",self.longitude);
NSLog(@"dLatitude : %f", self.latitude);
但我总是一直都是0。上面的代码是错的吗?要么 我没有为GPS定位设置我的模拟器?
我不明白为什么我在协调方面遇到了麻烦。
答案 0 :(得分:6)
首先,您的代码中存在以下几个问题:
-locationManager:didUpdateLocations:
和-locationManager:didFailWithError:
委托方法[locationMamager requestWhenInUseAuthorization];
或[locationMamager requestAlwaysAuthorization];
NSLocationWhenInUseUsageDescription
或NSLocationAlwaysUsageDescription
醇>
您可以使用Xcode模拟位置,查看来自Apple的信息:https://developer.apple.com/library/ios/recipes/xcode_help-debugger/articles/simulating_locations.html
答案 1 :(得分:1)
[CLLocationManager location]
会返回最近检索到的用户位置,但正如文档中所述:
如果从未检索到任何位置数据,则此属性的值为nil。
一开始,您的位置仍然未知。当CLLocationManager找到您的位置时,您应该使用委托方法做出反应。实现此方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
//User your location...
}
答案 2 :(得分:0)
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
BOOL shouldIAllow = FALSE;
NSString* locationStatus = @"";
switch (status) {
case kCLAuthorizationStatusRestricted:
locationStatus = @"Restricted Access to location";
break;
case kCLAuthorizationStatusDenied:
locationStatus = @"User denied access to location";
break;
case kCLAuthorizationStatusNotDetermined:
locationStatus = @"Status not determined";
default:
locationStatus = @"Allowed to location Access";
shouldIAllow = TRUE;
break;
}
if (shouldIAllow) {
NSLog(@"Location to Allowed");
// Start location services
[_locationManager startUpdatingLocation];
} else {
NSLog(@"Denied access: \(locationStatus)");
}
}