基于堆栈溢出中的一些代码示例,我创建了一个用于位置服务的类。当应用程序启动时,位置服务将立即启动,由上系统栏中的导航符号指示。我的应用程序只需要特定视图中的位置服务,所以我想激活/禁用特定事件上的位置服务。这可以降低能源消耗,提高客户的信心,只有在需要时才会使用定位服务。
首先,我定义了一个类LocationViewModel:
import SwiftUI
import Foundation
import Combine
import CoreLocation
import CoreMotion
class LocationViewModel: NSObject, ObservableObject
{
@Published var userLatitude: Double = 0
@Published var userLongitude: Double = 0
private let locationManager = CLLocationManager()
override init()
{
super.init()
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
// I tried this to access the startUpdatingLocation() method, but it did not work
func startUpdatingLocation()
{
self.locationManager.startUpdatingLocation()
}
}
extension LocationViewModel: CLLocationManagerDelegate
{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
guard let location = locations.last else { return }
userLatitude = location.coordinate.latitude
userLongitude = location.coordinate.longitude
}
}接下来,在一个特定的LocationView ( NavigationView的一部分)中,我创建了一个LocationViewModel类的实例:
import SwiftUI
struct LocationView : View
{
// some say, that a @StateObject is preferred over @ObservedObject, see:
// https://stackoverflow.com/questions/59620573/handle-swiftui-and-corelocation-with-mvvm-pattern
@ObservedObject var locationViewModel = LocationViewModel()
var body: some View
{
VStack
{
Text("Latitude: \(locationViewModel.userLatitude)")
Text("Longitude: \(locationViewModel.userLongitude)")
}
.navigationTitle("Location")
.navigationBarTitleDisplayMode(.inline)
}
}问题:
的效果吗?
当特定视图变为可见/不可更改时,
发布于 2021-05-31 09:12:00
解决方案:
我的错误是试图在locationViewModel.locationManager.startUpdatingLocation()之前调用方法来声明视图的主体。
.navigationTitle("Simulation")
.navigationBarTitleDisplayMode(.inline)
.onAppear(perform: {locationViewModel.locationManager.startUpdatingLocation()})
.onDisappear(perform: {locationViewModel.locationManager.stopUpdatingLocation()})https://stackoverflow.com/questions/67756026
复制相似问题