Reputation: 123
I try to learn something about asynchronous functions and I'm facing a nasty problem with Playground. I have a simple program to download some data, but unfortunately it crashes and all I get are these error messages:
error: execution stopped with unexpected state.
error: Execution was interrupted.
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
The source looks like this:
import Foundation
import PlaygroundSupport
func fetchNews() async -> Data? {
do {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
let (data, _) = try await URLSession.shared.data(from: url)
return data
} catch {
print("Failed to fetch data")
return nil
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
if let data = await fetchNews() {
print("Downloaded \(data.count) bytes")
} else {
print("Download failed.")
}
I thought that the line PlaygroundPage.current.needsIndefiniteExecution = true
would stop playground from exiting.
But I'm pretty sure I'm missing a very simple thing.
Upvotes: 0
Views: 154
Reputation: 17534
Add
PlaygroundPage.current.finishExecution()
to the end of your Playground page. (Xcode 16)
Upvotes: 0
Reputation: 534885
You cannot just say await
in the middle of nowhere; you have to be in an "async context", either an async
function or a Task. Just wrap your call in a Task:
func fetchNews() async -> Data? {
do {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")!
let (data, _) = try await URLSession.shared.data(from: url)
return data
} catch {
print("Failed to fetch data")
return nil
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
Task {
if let data = await fetchNews() {
print("Downloaded \(data.count) bytes")
} else {
print("Download failed.")
}
}
Result: Downloaded 83 bytes
Upvotes: 2