blob: 8a150b85e6b153513d60501cc61778d79bcb8a2d (
plain) (
blame)
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
|
//
// MessageFetcher.swift
// JuickNext
//
// Created by Vitaly Takmazov on 10.12.2019.
// Copyright © 2019 com.juick. All rights reserved.
//
import Foundation
import Combine
class MessageFetcher: ObservableObject {
@Published var state: Result<Root, FetchError>? = nil
init(url: String) {
guard let apiUrl = URL(string: url) else {
state = .failure(.error("Malformed API URL."))
return
}
URLSession.shared.dataTask(with: apiUrl) { [weak self] (data, _, error) in
if let error = error {
self?.state = .failure(.error(error.localizedDescription))
return
}
guard let data = data else {
self?.state = .failure(.error("Malformed response data"))
return
}
let root = try! JSONDecoder().decode(Root.self, from: data)
DispatchQueue.main.async { [weak self] in
self?.state = .success(root)
}
}.resume()
}
}
|