Skip to content

Instantly share code, notes, and snippets.

@erdemildiz
Created August 31, 2022 10:29
Show Gist options
  • Save erdemildiz/92246818653b9234ff696c36a02a871a to your computer and use it in GitHub Desktop.
Save erdemildiz/92246818653b9234ff696c36a02a871a to your computer and use it in GitHub Desktop.
enum PhotoListConstant {
static let listURL = "https://jsonplaceholder.typicode.com/photos"
}
enum NetworkError: Error {
case invalidURL
}
final class PhotoListViewModel: ObservableObject {
@Published var photoItems = [PhotoItemModel]()
@MainActor // 4
func fetchPhotoList() async {
guard let url = URL(string: PhotoListConstant.listURL) else {
fatalError(NetworkError.invalidURL.localizedDescription)
}
do {
// 5
let (data, _) = try await URLSession.shared.data(from: url)
let photoListData = try JSONDecoder().decode([PhotoItemModel].self, from: data)
// 6
self.photoItems = photoListData
} catch let error {
fatalError(error.localizedDescription)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment