swift Weather API + WidgetKit -“函数中的”异步“调用不支持并发”

oknrviil  于 2023-01-04  发布在  Swift
关注(0)|答案(1)|浏览(158)

我试图为iOS16WeatherKit制作一个TimelineProvider,我正在努力解决如何满足协议签名和使用新的异步API。
下面是我的代码:

struct WeatherProvider: TimelineProvider {
    
    func getSnapshot(in context: Context, completion: @escaping (WeatherEntry) -> ()) {       
        let weather = try? await WeatherService.shared.weather(for: currentLocation)        
        let entry = WeatherEntry(date: Date(), wind: nil, locationAuthStatus: nil)

        completion(entry)
    }

    // etc
}

编译此电极导线会引发构建错误'async' call in a function that does not support concurrency
自动修复建议:Add 'async' to function 'getSnapshot(in:completion:)' to make it asynchronous
但是如果你这样做了,结构体就不再符合:Type 'WeatherProvider' does not conform to protocol 'TimelineProvider'
这感觉应该是微不足道的,但我找不到任何例子说明如何做到这一点。

l7wslrjt

l7wslrjt1#

只需将所有内容放入Task中,就可以开始了。Task是将完成处理程序语法与新的async/await或更一般的在同步上下文中执行异步代码桥接起来的好方法:

Task{

    let weather = try? await WeatherService.shared.weather(for: currentLocation)        
    let entry = WeatherEntry(date: Date(), wind: nil, locationAuthStatus: nil)
    
    completion(entry)
}

相关问题