Resting

Swift

一个 Swift 包,为 HTTP REST 请求提供一个简化的接口,同时支持 Combine 和 async/await 模式。

特性

安装

您可以将此包添加到您的 Package.swift 文件的 dependencies 值中。

dependencies: [
    .package(url: "https://github.com/rocxteady/Resting.git", .upToNextMajor(from: "0.0.6"))
]

用法

1. 导入包

import Resting

2. 创建 RestClient 的实例

let clientConfiguration = RestClientConfiguration(sessionConfiguration: .default, jsonDecoder: .init())
let restClient = RestClient(configuration: clientConfiguration)

3. 配置您的请求

let requestConfig = RequestConfiguration(
    urlString: "https://api.example.com/data",
    method: .get
)

4. 发起 HTTP 调用

使用 async/await

// Decodable as response
do {
    let data: YourDecodableModel = try await restClient.fetch(with: requestConfig)
    // Handle the data
} catch {
    // Handle the error
}

// Data as response
do {
    let data = try await restClient.fetch(with: requestConfig)
    // Handle the data
} catch {
    // Handle the error
}

使用 Combine

// Decodable as response
let cancellable :AnyPublisher<YourDecodableModel, Error> = restClient.publisher(with: requestConfig)
cancellable.sink { completion in
    // Handle completion or error
} receiveValue: { (data: YourDecodableModel) in
    // Handle the data
}

// Data as response
restClient.publisher(with: requestConfig)
.sink { completion in
    // Handle completion or error
} receiveValue: { data in
    // Handle the data
}

错误处理

该包提供了一个专门的 RestingError 枚举来优雅地处理错误。它包括 .urlMalformed.statusCode.wrongParameterType.unknown 等案例。请务必将这些包含在您的错误处理逻辑中。

本地化

该包支持以下语言

如果您想贡献其他语言的翻译,请在我们的 GitHub 存储库上创建一个新的 issue 或提交一个 pull request。

贡献

我们感谢您的贡献!如果您有任何建议、功能请求或错误报告,请在我们的 GitHub 存储库上创建一个新的 issue。

许可

该包在 MIT 许可下可用。有关更多信息,请参见 LICENSE 文件。