gpt4 book ai didi

iphone - didUpdateLocations 被调用,但发送了错误的位置

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:22:34 25 4
gpt4 key购买 nike

我正在使用核心位置来获取 iPhone 的位置。我还为我的 viewcontroller 文件实现了委托(delegate)协议(protocol),并创建了一个 CLLocationmanager 对象。

当我按下按钮 (IBAction) 时,我希望位置得到更新。委托(delegate)被正确调用。我可以看到,因为 NSLog 消息出现时带有纬度/经度坐标。

但是当我在 IOS 模拟器中更改位置并尝试使用按钮再次访问该位置时,我得到的位置输出保持不变。我必须再次按下按钮才能获得正确的位置。显然,我希望第一次按下按钮时位置正确

这是我触发委托(delegate)的按钮:

- (IBAction)getLocation:(id)sender {


[locationManager startUpdatingLocation];
}

我的 viewDidLoad 中有这段代码

locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;

这是我的委托(delegate)方法:

#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 didUpdateLocations:(NSArray *)locations{
NSLog(@"didUpdateToLocation: %@", [locations lastObject]);
CLLocation *currentLocation = [locations lastObject];


if (currentLocation != nil) {
_longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
[locationManager stopUpdatingLocation];
}

我在 Iphone 6.1 模拟器中运行我的代码..

最佳答案

来自 Apple 引用资料:CLLocationManager

Because it can take several seconds to return an initial location, the location manager typically delivers the previously cached location data immediately and then delivers more up-to-date location data as it becomes available.

也在另一个堆栈溢出帖子(https://stackoverflow.com/questions/12858548/cllocationmanager-holds-cache-value)中回答,使用 CLLocation 的时间戳属性过滤掉返回的旧缓存位置对象。我选择了 15 秒来确保区分缓存的对象,但即使只有几秒钟也可能就足够了:

NSTimeInterval timeInterval = [[location timestamp] timeIntervalSinceNow];
if (abs((NSInteger)timeInterval) < 15)
{
//do something
}

关于iphone - didUpdateLocations 被调用,但发送了错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com