【发布时间】:2021-07-16 14:30:45
【问题描述】:
我正在尝试在屏幕上显示用户位置坐标,但当我运行应用程序时没有任何显示,即使我可以在控制台中看到坐标。我遇到的第二个问题是当我按下停止按钮时,位置更新不会停止。
位置管理器:
import Foundation
import CoreLocation
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init(){
super.init()
locationManager.delegate = self
}
func startTracking() {
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
func stopTracking() {
print("stop test")
locationManager.stopUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = false
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let tempLocation = locations.last?.coordinate
print(tempLocation)
DispatchQueue.main.async {
self.location = tempLocation
}
}
}
查看:
import SwiftUI
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack{
startLocationTrackingButton()
stopLocationTrackingButton()
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
}
}
}
struct startLocationTrackingButton: View{
@StateObject var locationManager = LocationManager()
var body: some View{
Button("START"){
locationManager.startTracking()
}
}
}
struct stopLocationTrackingButton: View{
@StateObject var locationManager = LocationManager()
var body: some View{
Button("STOP"){
locationManager.stopTracking()
}
}
}
感谢您的帮助!
【问题讨论】:
标签: swift swiftui core-location