|
| 1 | +// |
| 2 | +// File.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Lukas Schmidt on 19.12.21. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 11 | +public extension NetworkService { |
| 12 | + |
| 13 | + /** |
| 14 | + Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. |
| 15 | + |
| 16 | + **Example**: |
| 17 | + ```swift |
| 18 | + let networkService: NetworkService = // |
| 19 | + let resource: Resource<String> = // |
| 20 | + |
| 21 | + let (result, response) = try await networkService.request(resource) |
| 22 | + ``` |
| 23 | + |
| 24 | + - parameter resource: The resource you want to fetch. |
| 25 | + |
| 26 | + - returns: a touple containing the parsed result and the HTTP response |
| 27 | + - Throws: A `NetworkError` |
| 28 | + */ |
| 29 | + @discardableResult |
| 30 | + func request<Result>(_ resource: Resource<Result>) async throws -> (Result, HTTPURLResponse) { |
| 31 | + return try await withCheckedThrowingContinuation({ coninuation in |
| 32 | + request(resource: resource, onCompletionWithResponse: { |
| 33 | + coninuation.resume(with: $0) |
| 34 | + }) |
| 35 | + }) |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + Fetches a resource asynchronously from remote location. Execution of the requests starts immediately. |
| 40 | + |
| 41 | + **Example**: |
| 42 | + ```swift |
| 43 | + let networkService: NetworkService = // |
| 44 | + let resource: ResourceWithError<String, CustomError> = // |
| 45 | + |
| 46 | + let (result, response) = try await networkService.request(resource) |
| 47 | + ``` |
| 48 | + |
| 49 | + - parameter resource: The resource you want to fetch. |
| 50 | + |
| 51 | + - returns: a touple containing the parsed result and the HTTP response |
| 52 | + - Throws: Custom Error provided by ResourceWithError |
| 53 | + */ |
| 54 | + @discardableResult |
| 55 | + func request<Result, E: Error>(_ resource: ResourceWithError<Result, E>) async throws -> (Result, HTTPURLResponse) { |
| 56 | + return try await withCheckedThrowingContinuation({ coninuation in |
| 57 | + request(resource: resource, onCompletionWithResponse: { |
| 58 | + coninuation.resume(with: $0) |
| 59 | + }) |
| 60 | + }) |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments