【发布时间】:2021-10-31 15:18:43
【问题描述】:
我试图把这个例子放到一个简单的项目 + ViewController 中但无法编译 https://www.hackingwithswift.com/quick-start/concurrency/how-to-get-a-result-from-a-task
我正在尝试通过点击按钮从 IBAction 调用 fetchQuotes(),但是因为 fetchQuotes 被标记为 async,所以我遇到了错误。
我知道我可以将对fetchQuotes() 的调用封装在一个任务中:
Task {
fetchQuotes()
}
,但这对我来说没有意义,因为fetchQuotes 已经在创建任务了。
谁能给点建议?
这是我的代码:
// https://www.hackingwithswift.com/quick-start/concurrency/how-to-get-a-result-from-a-task
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonTap(_ sender: Any) {
fetchQuotes()
}
func fetchQuotes() async {
let downloadTask = Task { () -> String in
let url = URL(string: "https://hws.dev/quotes.txt")!
let data: Data
do {
(data, _) = try await URLSession.shared.data(from: url)
} catch {
throw LoadError.fetchFailed
}
if let string = String(data: data, encoding: .utf8) {
return string
} else {
throw LoadError.decodeFailed
}
}
let result = await downloadTask.result
do {
let string = try result.get()
print(string)
} catch LoadError.fetchFailed {
print("Unable to fetch the quotes.")
} catch LoadError.decodeFailed {
print("Unable to convert quotes to text.")
} catch {
print("Unknown error.")
}
}
}
enum LoadError: Error {
case fetchFailed, decodeFailed
}
【问题讨论】:
-
请将您的代码和错误消息发布为文本而不是图像。
-
将结果集设置为类变量
-
我已将代码添加为文本(我希望编译器错误显示抱歉!)
标签: swift concurrency task