我正在使用Core Location框架来获取iOS中的位置。我使用CLLocationManager *locationManager;
并致电[locationManager startUpdatingLocation];
问题是我只需要即时位置,但startUpdatingLocation
继续给我定位。为了阻止这种情况,我可以使用[self.locationManager stopUpdatingLocation]
,但这看起来像是出路或黑客。
有没有更好的方法来获取iOS中的当前位置?
答案 0 :(得分:2)
#import <CoreLocation/CoreLocation.h>
@interface LocationSearchViewController : UIViewController<UITextFieldDelegate,CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
}
你的.m文件中的
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
[locationManager stopUpdatingLocation]; // when u got the lat and long it stop uoatde the location
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *getcurrlong = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
NSSting *getcurrlat = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
}
答案 1 :(得分:2)
您无法用精确的术语来考虑位置。您将从位置管理员处获得越来越准确的位置,由您决定何时准确。你必须权衡能耗和时间。位置更新永远不会完全准确。永远不会立即归还。设备必须为硬件供电,然后收听GPS / WiFi / Cell信号并使用所有这些来计算位置。
没有办法要求“我当前的精确位置”并立即将其提供给您。位置不是[NSDate date]
之类的属性。您只能要求最佳估计位置更新,它们只会以不精确的测量结果向您发送,而且不会立即(除了缓存位置)。
答案 2 :(得分:0)
检查
-(void)getCurrentLocation
{
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
startLocation = nil;
}
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (startLocation == nil)
{
startLocation = newLocation;
[locationManager setDelegate:nil];
locationManager = nil;
}
}