您可以使用 SwiftErickNetwork 包轻松进行网络操作。
SwiftErickNetwork 提供了一个名为 NetworkConfigurable 的蓝图,用于轻松创建 EndPoints,并提供了一个 NetworkManager 来无缝地进行网络连接和解码任务。
NetworkConfigurable 为 EndPoints 提供了一个蓝图,帮助创建和管理应用程序中使用的各种 API EndPoints。
此外,它还支持 url()
和 urlRequest()
函数,方便您直接使用 URL 或 URLRequest 实例。
public protocol NetworkConfigurable {
associatedtype Response
var baseURL: String { get }
var path: String { get }
var queryParameters: [URLQueryItem]? { get }
var httpMethod: HttpMethod { get }
var httpHeaderFields: [String: String]? { get }
var httpBody: Encodable? { get }
}
NetworkManager 使用 URL 或 EndPoint 可以轻松进行网络连接和解码。 当使用 EndPoint 执行网络操作时,它会使用 EndPoint 指定的 Response 类型返回解码后的数据。
此外,它还提供了 requestPublisher(with:)
函数和 request(with:) async
函数,可以使用 Combine 和并发进行异步处理。
public protocol NetworkManageable {
var urlSession: URLSessionProtocol { get }
func request<DTO: Decodable, EndPoint: NetworkConfigurable>(
with endpoint: EndPoint,
completion: @escaping (Result<DTO, NetworkError>) -> Void
) where EndPoint.Response == DTO
func request(
with url: URL,
completion: @escaping (Result<Data, NetworkError>) -> Void
)
func requestPublisher<DTO: Decodable, EndPoint: NetworkConfigurable>(
with endpoint: EndPoint
) -> AnyPublisher<DTO, NetworkError> where EndPoint.Response == DTO
func requestPublisher(with url: URL) -> AnyPublisher<Data, NetworkError>
func request<DTO: Decodable, EndPoint: NetworkConfigurable>(
with endpoint: EndPoint
) async -> Result<DTO, NetworkError> where EndPoint.Response == DTO
func request(with url: URL) async -> Result<Data, NetworkError>
}