|
| 1 | +// |
| 2 | +// ProductFetcher.swift |
| 3 | +// Products |
| 4 | +// |
| 5 | +// Created by Mat Schmid on 2019-06-10. |
| 6 | +// Copyright © 2019 Shopify. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | +import SwiftUI |
| 11 | +import Combine |
| 12 | + |
| 13 | +enum LoadableState<T> { |
| 14 | + case loading |
| 15 | + case fetched(Result<T, FetchError>) |
| 16 | +} |
| 17 | + |
| 18 | +enum FetchError: Error { |
| 19 | + case error(String) |
| 20 | + |
| 21 | + var localizedDescription: String { |
| 22 | + switch self { |
| 23 | + case .error(let message): |
| 24 | + return message |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +class ProductFetcher: BindableObject { |
| 30 | + private static let apiUrlString = "https://gist.githubusercontent.com/schmidyy/02fdec9b9e05a71312a550fc50f948e6/raw/7fc2facbbf9c3aa526f35a32d0c7fe74a4fc29a1/products.json" |
| 31 | + var didChange = PassthroughSubject<ProductFetcher, Never>() |
| 32 | + |
| 33 | + var state: LoadableState<Root> = .loading { |
| 34 | + didSet { |
| 35 | + didChange.send(self) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + init() { |
| 40 | + guard let apiUrl = URL(string: ProductFetcher.apiUrlString) else { |
| 41 | + state = .fetched(.failure(.error("Malformed API URL."))) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + URLSession.shared.dataTask(with: apiUrl) { [weak self] (data, _, error) in |
| 46 | + if let error = error { |
| 47 | + self?.state = .fetched(.failure(.error(error.localizedDescription))) |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + guard let data = data else { |
| 52 | + self?.state = .fetched(.failure(.error("Malformed response data"))) |
| 53 | + return |
| 54 | + } |
| 55 | + let root = try! JSONDecoder().decode(Root.self, from: data) |
| 56 | + |
| 57 | + DispatchQueue.main.async { [weak self] in |
| 58 | + self?.state = .fetched(.success(root)) |
| 59 | + } |
| 60 | + }.resume() |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +class ImageFetcher: BindableObject { |
| 65 | + var didChange = PassthroughSubject<Data, Never>() |
| 66 | + |
| 67 | + var data: Data = Data() { |
| 68 | + didSet { |
| 69 | + didChange.send(data) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + init(url: String) { |
| 74 | + guard let imageUrl = URL(string: url) else { |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + URLSession.shared.dataTask(with: imageUrl) { (data, _, _) in |
| 79 | + guard let data = data else { return } |
| 80 | + DispatchQueue.main.async { [weak self] in |
| 81 | + self?.data = data |
| 82 | + } |
| 83 | + }.resume() |
| 84 | + } |
| 85 | +} |
0 commit comments