gpt4 book ai didi

swift - 我试图在 Swift 3 中以设定的时间间隔获取位置更新,但它每个时间间隔都会运行我的函数很多次,它应该只运行一次

转载 作者:行者123 更新时间:2023-11-30 12:41:53 30 4
gpt4 key购买 nike

我使用 locationManager.startUpdatingLocation() 获取用户的位置,然后调用一个处理我所有逻辑的函数,问题是它似乎被调用了多次,我不知道为什么。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")

long = locValue.longitude
lat = locValue.latitude

if(self.arrayOfCellData.count > 0)
{

for i in 0...self.arrayOfCellData.count-1
{
getdistance(lat0: self.arrayOfCellData[i].shop.latitude!, long0: self.arrayOfCellData[i].shop.longitude!, lat1: locValue.latitude, long1: locValue.longitude)
{distance in

self.arrayOfCellData[i].meterstolocation = distance
}
}
DispatchQueue.main.async {
self.myTable.reloadData()
}
}
print("stopped updating")
locationManager.stopUpdatingLocation()
}

var run: Bool = true;

func updateLocations()
{
if(run)
{
run = false;
}
else
{
locationManager.startUpdatingLocation()
}
}

override func viewDidLoad() {
super.viewDidLoad()
//

locationManager.requestAlwaysAuthorization()
//
//
//
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.startUpdatingLocation()

Timer.scheduledTimer(timeInterval: 10,
target: self,
selector: #selector(self.updateLocations),
userInfo: nil,
repeats: true)
}

我的输出是:

locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354
stopped updating
locations = 37.33228724 -122.05833354

输出本身是正确的,但它一口气输出了多个打印内容。而且我不希望代码多次运行,每个时间间隔只运行一次。

最佳答案

获取位置后不应调用 locationManager.stopUpdatingLocation(),并且不需要计时器。只需在开始时调用一次 locationManager.startUpdatingLocation() ,它就会自动向您发送更新,但仅当位置发生变化时。请参阅文档 https://developer.apple.com/reference/corelocation/cllocationmanager

关于swift - 我试图在 Swift 3 中以设定的时间间隔获取位置更新,但它每个时间间隔都会运行我的函数很多次,它应该只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134882/

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