Swift 软件包以简化、轻量级和可扩展的方式发出简单的 REST API 请求

休息套件

声音副本 (819 × 375 px)-2

RESTKit 是一个轻量级的 Swift 包,用于发出基本的 HTTP 请求和处理响应。它提供了一个名为 Request 的简单协议,您可以使用该协议来定义自己的 HTTP 请求(通过仅提供必要的部分),然后使用send()

安装

您可以使用 Swift Package Manager 安装 RESTKit。要将 RESTKit 添加到 Xcode 项目中,请选择“> Swift Packages 的文件”>“添加 Package 依赖项”,然后输入以下 URL:

https://github.com/your_username/restkit.git

Usage

To use RESTKit in your Swift package, you first need to define a struct or class that conforms to the Request protocol. The Request protocol defines the properties and methods that your request must have, including the URL, HTTP method, headers, and body. You can also define an associated type that specifies the type of the response data that your request expects.

Here’s an example of a simple Request implementation that sends a GET request to an API endpoint:

struct MyRequest: Request {
    typealias RemoteModel = MyResponseModel

    var url: URL? = "https://api.example.com/data"
    var method: HTTPMethod = .get
    var header: [String: String] { ... }
    var body: Data? { ... }
}

By default, header and body are nil.

Once you’ve defined your Request, you can create an instance of it and call the send() method to send the request and retrieve the response data:

let request = MyRequest()
let response = await request.send()

The send() method returns a Result object that contains the decoded response data or an error.

Contributing

Contributions are welcome! If you find a bug, have a feature request, or want to contribute code, please open an issue or submit a pull request on GitHub.

License

RESTKit is released under the MIT license. See LICENSE for details.

GitHub

点击跳转