用于 URLSession 的异步封装器和依赖注入层。其核心是 NetworkServiceClient
协议以及一个最小化的实现 NetworkService
。
该库提供的一个显著便利是 TopLevelCodable
协议,它使得对符合类型的轻松编码和解码成为可能。该协议将 TopLevelEncoder
和 TopLevelDecoder
与给定类型关联,以便库可以使用它,而无需显式地将其作为参数传递。此外,还包括了 TopLevelEncodable
和 TopLevelDecodable
。
import NetworkService
let networkService = NetworkService()
let url = URL(string: "http://www.foobar.com")!
struct Foo: TopLevelCodable {
static var encoder: JSONEncoder { JSONEncoder() }
static var decoder: JSONDecoder { JSONDecoder() }
let bar: Int
}
let foo = Foo(bar: 0)
let result: Result<Foo, NetworkService.Failure> = await networkService.get(url)
let foo = try result.get()
print(foo.bar)
let result: Result<Foo, NetworkService.Failure> = await networkService.post(foo, to: url)
let foo = try result.get()
print(foo.bar)
let result: Result<Foo, NetworkService.Failure> = await networkService.put(foo, to: url)
let foo = try result.get()
print(foo.bar)
let result: Result<Foo, NetworkService.Failure> = await networkService.get(url)
let foo = try result.get()
print(foo.bar)
var request = URLRequest(url: url)
request.method = .GET
let result = await networkService.start(request)
let foo = try result.get()
print(foo.bar)
提供用于测试的 NetworkServiceClient
的实现 MockNetworkService
。 支持为所有网络函数定义设置输出值、重复值和延迟响应。
目前,仅支持 Swift Package Manager。