The following code fails on Swift Playgrounds for Mac but not Swift Playgrounds for iPad:
import SwiftUI
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
struct ContentView: View {
@State private var results = [Result]()
var body: some View {
List(results, id: \.trackId) { item in
VStack(alignment: .leading) {
Text(item.trackName)
.font(.headline)
Text(item.collectionName)
}
}
.task {
results = await loadData()
}
}
}
func loadData() async -> [Result]{
var results = [Result(trackId: -1, trackName: "No Tracks Available", collectionName: "No Collection Available")]
let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song")
do {
let (data, _) = try await URLSession.shared.data(from: url!)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
results = decodedResponse.results
}
} catch {
print("Invalid data")
}
return results
}
Repost of https://developer.apple.com/forums/thread/708856 which I think was incorrectly accepted as answered. Example from https://www.hackingwithswift.com/books/ios-swiftui/sending-and-receiving-codable-data-with-urlsession-and-swiftui
Post
Replies
Boosts
Views
Activity
I have an app using UrlSession in Swift Playgrounds for iPad, and everything worked great.
I opened the same code in Swift Playgrounds for Mac, and the line:
let (data, _) = try await URLSession.shared.data(from: url)
silently fails everytime. I exported a small snippet to a playground in Mac, and found that adding:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
At the beginning of the script fixes this in the playground. I am wondering if there is a way to move this code to the app version and get this up and running on the Mac? Or maybe this code was never designed to run on a Macbook?