Created
August 31, 2022 10:29
-
-
Save erdemildiz/92246818653b9234ff696c36a02a871a to your computer and use it in GitHub Desktop.
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
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