You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让按钮触发的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 08:05:22