【发布时间】:2025-12-23 00:15:11
【问题描述】:
我正在开发一个应用程序,它可以跟踪用户的位置并将一些与该位置相关的数据保存在 CoreData 中。我是 SwiftUI 新手,所以我的问题与应用程序中将位置数据保存到 CoreData 的最佳位置/位置有关。
目前,我的设置与此处接受的解决方案非常相似: How to get Current Location using SwiftUI, without ViewControllers?
因此,我不会重复上面链接中已经存在的代码,但会引用它。因此,在阅读我的问题陈述的其余部分之前,您可能想先看看答案。
所以在 LocationManager 类中我有:
@Published var userLocations: [CLLocation]? {
willSet {
objectWillChange.send()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
let howOldIsTheLastLocationData = abs(location.timestamp.timeIntervalSinceNow)
if howOldIsTheLastLocationData < 15 && location.horizontalAccuracy > 0 && location.horizontalAccuracy < 15 {
if userLocations == nil {
userLocations = []
}
userLocations?.append(location)
}
print(#function, location, location.latitudeString, location.longitudeString, location.altitude, howOldIsTheLastLocationData)
}
因此,userLocations 是我想在我的视图中观察并保存到我的 CoreData 中的内容。
现在在我看来,我有:
@Environment(\.managedObjectContext) var context
@State var segment: Segment?
@ObservedObject var locationManager = LocationManager()
var userPath: [CLLocationCoordinate2D]? {
if let userLocations = locationManager.userLocations {
return userLocations.map( { $0.coordinate })
}
return nil
}
var body: some View {
// A MapView Uses userPath to show the path on a MKMapView
MapView(pathCoordinates: userPath ?? [])
// There is a button that by pressing it, it creates a Segment which is an Entity in my CoreData with time data.
}
到目前为止,我上面提到的一切都在工作。我正在获取位置更新,在 MapView 上显示路径。我可以通过按开始按钮来创建分段(并保存到 CoreData)。现在我正在寻找的部分是针对进入 userLocations 的每个位置更新,我想创建另一个名为 PointOnPath 的 CoreData 实体的新实例,它与一个段关联。所以 Segment 与 PointOnPath 是一对多的关系。我不知道我应该在哪里调用类似以下代码行的代码:
let point = PointOnPath(context: context)
point.latitude = location.coordinate.latitude
point.longitude = location.coordinate.longitude
point.segment = segment
try? context.save()
我想过把上面几行代码放到:
var userPath: [CLLocationCoordinate2D]? {
if let userLocations = locationManager.userLocations {
// Maybe add to CoreData for PointOnPath here?
return userLocations.map( { $0.coordinate })
}
return nil
}
但我注意到这被多次调用。在我看来,它应该只在发生新的 userLocations?.append(location) 时才被调用,但事实并非如此,它被调用的次数比 userLocations?.append(location) 发生的次数多得多。一般来说,我不确定这是否是在 PointOnPath 中保存位置数据的最佳位置。任何见解都非常感谢。
【问题讨论】:
标签: ios swift core-data swiftui core-location