gpt4 book ai didi

iOS swift 位置管理器未正确更新

转载 作者:行者123 更新时间:2023-11-30 13:20:04 25 4
gpt4 key购买 nike

我正在使用CLLocationManager来获取用户位置。我需要在用户移动时更新他们的位置。我正在使用这段代码:

import UIKit

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

private var locationManager = CLLocationManager()
lazy var locations = [CLLocation]()
var op:String = ""
@IBOutlet weak var resultTxt: UITextView!

@IBAction func Start(sender: AnyObject) {
startLocationManager()
showResult()
}
override func viewDidLoad() {
super.viewDidLoad()
}

func startLocationManager(){
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}

func startLocationTracking() {
NSLog("startLocationTracking")
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .NotDetermined, .Restricted, .Denied:
print("No access")
self.startLocationManager()
case .AuthorizedAlways, .AuthorizedWhenInUse:
NSLog("authorizationStatus authorized")
}
} else {
print("Location services are not enabled")
self.startLocationManager()
}
}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
let howRecent = location.timestamp.timeIntervalSinceNow

if abs(howRecent) < 10 && location.horizontalAccuracy < 20 {
//update distance
self.locations.append(location)
showResult()
}
}
}

func showResult(){
let currentDate = NSDate()
let res:String = "Result LAT : \(self.locations.last?.coordinate.latitude) AND LNG : \(self.locations.last?.coordinate.longitude) Time : \(currentDate.toShortTimeString()) \n "
op += res
self.resultTxt.text = op
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

}

我已经在 .plist 中添加了 NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 。这段代码第一次运行得很好。但是,当用户移动“didUpdateLocations”时,不会被解雇。谁能帮帮我,我做错了什么?

最佳答案

尝试添加这些行,以便能够在用户移动时监视显着的位置变化:

locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 300 //value is up to you

关于iOS swift 位置管理器未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857229/

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