-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sending and receiving Codable data with URLSession
- Loading branch information
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
56 changes: 56 additions & 0 deletions
56
SwiftUI-Apprentic/SwiftUI-Apprentic/Views/Demos/Network/NetworkView.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// | ||
// NetworkView.swift | ||
// SwiftUI-Apprentic | ||
// | ||
// Created by zzz on 2022/1/18. | ||
// | ||
|
||
import SwiftUI | ||
|
||
struct Response: Codable { | ||
var results: [Result] | ||
} | ||
|
||
struct Result: Codable { | ||
var trackId: Int | ||
var trackName: String | ||
var collectionName: String | ||
} | ||
|
||
struct NetworkView: 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 { | ||
await loadData() | ||
} | ||
} | ||
|
||
func loadData() async { | ||
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else { | ||
print("Invalid URL") | ||
return | ||
} | ||
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") | ||
} | ||
} | ||
} | ||
|
||
struct NetworkView_Previews: PreviewProvider { | ||
static var previews: some View { | ||
NetworkView() | ||
} | ||
} |