如何让按钮触发的fetch()等待update()执行完毕后再运行?
问题描述
我有一个由CLLocationManager调用的update()函数,该函数需耗时向服务器更新数据。UI中的fetch()函数由按钮触发,要求仅在按钮触发时执行,且需等待update()执行完毕后再运行;若update()未在运行,则立即执行。此前的相关提问未解决我的问题,以下是最小可复现示例代码:
import SwiftUI import CoreLocation class ExampleManager: ObservableObject { func fetch() { print("these would be some results") } } struct ContentView2: View { @StateObject var locationManager = LocationManager() @StateObject var example = ExampleManager() var body: some View { Button { example.fetch() } label: { Text("fetch") } } } class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate { // .. CLLocationManager的必要配置代码 private func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) async { guard let newLocation: CLLocation = locations.first else { return } await update(newLocation: newLocation) } func update(newLocation: CLLocation) async { print("1") try! await Task.sleep(nanoseconds: 10_000_000_000) print("2") } }
内容的提问来源于stack exchange,提问作者ambassador
相关产品推荐
相关产品推荐

