-
Notifications
You must be signed in to change notification settings - Fork 4
/
AsyncService.swift
53 lines (41 loc) · 1.41 KB
/
AsyncService.swift
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// AsyncService.swift
// AsyncNetworkServiceExample
//
// Created by Matt Kiazyk on 2022-01-21.
//
import AsyncNetworkService
import Foundation
// Example of using a Rest API
class GiphyService {
let routes: Routes
var networkService: AsyncHTTPNetworkService
struct Routes {
var baseRequestBuilder: URLRequestBuilder { return URLRequestBuilder(baseURL: URL(string: "https://api.giphy.com/v1")!) }
func getRandomGif() -> URLRequest {
return baseRequestBuilder.get("gifs/random")
}
}
init() {
routes = Routes()
networkService = AsyncHTTPNetworkService(requestModifiers: [APIKeyRequestModifier(apiKey: "FitddX5BlIIpURiBMZJRmSDDV8MBEgBf")])
}
/// Example api call to return a random gif url
func getRandomGif(tag: String, rating: String = "g") async throws -> URL {
let urlRequest = routes.getRandomGif().queryItems([
"tag": tag,
"rating": rating,
])
let requestTask = Task { () -> GiphyDataWrapper in
try await networkService.requestObject(urlRequest)
}
let result = await requestTask.result
switch result {
case let .failure(error):
print("ERROR LOADING GIF: \(error.localizedDescription)")
throw error
case let .success(giphy):
return URL(string: giphy.data.images.downsizedLarge.url)!
}
}
}