-
Notifications
You must be signed in to change notification settings - Fork 0
/
ItuneDataFetcher.swift
52 lines (44 loc) · 1.4 KB
/
ItuneDataFetcher.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
// ItuneDataFetcher.swift
// project!
//
// Created by pads on 2022/12/21.
//
import Foundation
class ItunesDataFetcher: ObservableObject {
@Published var items = [StoreItem]()
@Published var showError = false
var error: Error? {
willSet {
DispatchQueue.main.async {
self.showError = newValue != nil
}
}
}
enum FetchError: Error {
case invalidURL
}
func fetchData(term: String) {
let urlString = "https://itunes.apple.com/search?term=\(term)&media=music&country=tw"
guard let urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: urlString) else {
error = FetchError.invalidURL
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data {
do {
let searchResponse = try JSONDecoder().decode(SearchResponse.self, from: data)
DispatchQueue.main.async {
self.items = searchResponse.results
self.error = nil
}
} catch {
self.error = error
}
} else if let error {
self.error = error
}
}.resume()
}
}