APIManager
APIManager 是一个用于抽象 RESTful API 请求的框架。
要求
- iOS 11.0+
- Swift 4.2+
安装
CocoaPods
CocoaPods 是 Cocoa 项目的依赖管理器。您可以使用以下命令安装它
$ gem install cocoapods
要求 CocoaPods 1.0.0+ 来构建 APIManager。
要使用 CocoaPods 将 APIManager 集成到您的 Xcode 项目中,请在您的 Podfile
中指定它
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.0'
use_frameworks!
target '<Your Target Name>' do
pod 'APIManager', '~> 0.3.0'
end
然后,运行以下命令
$ pod install
注意
APIManager 0.0.5 是支持 Swift 3 的最后一个版本
Swift 包管理器
Swift 包管理器 是一个自动化分发 Swift 代码的工具,并集成到 swift
编译器中。
一旦你设置了 Swift 包,将 APIManager 添加为依赖项就像将其添加到 Package.swift
的 dependencies
值一样简单。
dependencies: [
.Package(url: "https://github.com/rauhul/api-manager.git", from: "0.3.0")
]
使用方法
APIManager 依赖于用户为它们正在工作的 RESTful API 创建相关联的 APIServices
和 APIReturnable
类型。 APIServices
包含各种端点的描述,作为原生 swift 对象返回它们的响应。
创建 APIReturnable 类型
APIReturnable 类型只需遵守一个方法 init(from: Data) throws
。 APIManager 扩展 Decodable
类型以也符合 APIReturnable
。一个示例实现如下
extension APIReturnable where Self: Decodable {
init(from data: Data) throws {
self = try JSONDecoder().decode(Self.self, from: data)
}
}
创建 APIService
APIService 由 3 个组件组成。
- 一个
baseURL
。该服务中的端点将被追加到该 URL 段。因此,baseURL 通常看起来是服务通信的 API 的根 URL。
open class var baseURL: String {
return "https://api.example.com"
}
- 将与您
APIService
中的端点发出的APIRequest
一起发送的HTTPHeaders
。
open class var headers: HTTPHeaders? {
return [
"Content-Type": "application/json"
]
}
- 您想要使用的RESTful API端点集。这些端点应该是对
APIRequest
构造函数的简单封装,可以接受数据(以HTTPParameters
和/或HTTPBody
作为JSON字典[String: Any]
)。例如,如果您想通过ID获取用户信息,该端点可能如下所示
open class func getUser(byId id: Int) -> APIRequest<ExampleReturnType> {
return APIRequest<ExampleReturnType>(service: Self, endpoint: "/users", params: ["id": id], body: nil, method: .GET)
}
使用APIService
现在您有了APIService
,就可以用它来发送RESTful API请求。
我们需要访问的所有RESTful API端点都应该已经在我们的APIService
中定义,因此使用它们只是调用它们的问题。
使用上面的示例服务,我们可以发送请求来获取与ID 452398关联的用户
let request = ExampleService.getUser(byId: 452398)
然后使用以下方式执行APIRequest
request.perform(withAuthorization: nil)
但是,这使得我们无法访问响应或潜在的错误,并且还需要多行代码来完成一个实际的动作。方便的是APIManager
允许我们通过简单的链式语法来解决这个问题。我们可以指定成功、取消和失败块。下面的新请求如下
ExampleService.getUser(byId: 452398)
.onSuccess { (returnValue: ReturnType) in
// Handle Success (Background thread)
DispatchQueue.main.async {
// Handle Success (main thread)
}
}
.onFailure { (error) in
// Handle Failure (Background thread)
DispatchQueue.main.async {
// Handle Failure (main thread)
}
}
.perform(withAuthorization: nil)
支持
贡献
请使用Github Flow进行贡献。创建一个分支,添加提交,并发起一个pull request。
许可协议
本项目受MIT许可协议许可。有关此许可协议的完整副本,请查看LICENSE文件。