我有以下几行代码来定位我的位置,但无论我在哪里,我都会得到相同的位置:
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
[locationManager startUpdatingLocation];
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *location = [locations lastObject];
self.lati = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
self.longi = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
[locationManager stopUpdatingLocation];
locationManager.delegate = nil;
}
答案 0 :(得分:0)
使用此委托方法代替您的委托方法。它会对你有用。
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
myLatitude = newLocation.coordinate.latitude;
myLongitude = newLocation.coordinate.longitude;
NSLog(@"LAT AND LON IS %f %f",myLatitude,myLongitude);
}
答案 1 :(得分:0)
in .h write
<CLLocationManagerDelegate>
then this also
CLGeocoder *geocoder;
CLLocationManager *locationManager;
then in .m
locationManager = [[CLLocationManager alloc] init] ;
locationManager.delegate = self;
[CLLocationManager locationServicesEnabled];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLHeadingFilterNone;
[locationManager startUpdatingLocation];
and then implement its delegates
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation(CLLocation*)newLocation fromLocation:(CLLocation *)oldLocation
{
[manager stopUpdatingLocation];
userCoordinate=newLocation.coordinate;
[[NSUserDefaults standardUserDefaults] setFloat:userCoordinate.latitude
forKey:@"userLat"];
[[NSUserDefaults standardUserDefaults] setFloat:userCoordinate.longitude
forKey:@"userLong"];
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks)
{
NSString *cityName = @"";
NSString *countryName = @"";
cityName = [placemark.addressDictionary valueForKey:@"City"];
countryName = [placemark.addressDictionary valueForKey:@"Country"];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:cityName forKey:@"CityName"];
[prefs setObject:countryName forKey:@"CountryName"];
}
}];
[manager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
[manager stopUpdatingLocation];
if(error.code == kCLErrorDenied)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"You have to select \"Allow\" for current location." delegate:self cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
alert.tag = 888;
[alert show];
}
[[NSUserDefaults standardUserDefaults] setFloat:0.0
forKey:@"userLat"];
[[NSUserDefaults standardUserDefaults] setFloat:0.0
forKey:@"userLong"];
[manager stopUpdatingLocation];
}