Slide 36
Slide 36 text
extension Client {
func fetch
Item(id: Int,
completion:
@escaping (Result<
Item, Error>) -> Void)
{
let urlRequest = URLRequest(url: baseURL
.appendingPathComponent("
items")
.appendingPathComponent("\(id)")
)
let session = URLSession.shared
session.dataTask(with: urlRequest) {
(data, _, error) in
if let error = error {
completion(.failure(error))
}
else if let data = data {
let decoder = JSONDecoder()
completion(Result {
try decoder.decode(
Item.self,
from: data)
})
}
}.resume()
}
}
extension Client {
func fetch
User(id: Int,
completion:
@escaping (Result<
User, Error>) -> Void)
{
let urlRequest = URLRequest(url: baseURL
.appendingPathComponent("
users")
.appendingPathComponent("\(id)")
)
let session = URLSession.shared
session.dataTask(with: urlRequest) {
(data, _, error) in
if let error = error {
completion(.failure(error))
}
else if let data = data {
let decoder = JSONDecoder()
completion(Result {
try decoder.decode(
User.self,
from: data)
})
}
}.resume()
}
}