可乐
可乐是 E-sites iOS Suite 的一部分。
E-sites Swift iOS API 客户端用于标准的 restful API,默认支持 OAuth2。
安装
### Swift PM
package.swift 依赖项
.package(url: "https://github.com/e-sites/cobalt.git", from: "7.0.0"),
并在您的应用程序/库目标中,将 "Cobalt"
添加到您的 dependencies
中,例如:
.target(name: "BestExampleApp", dependencies: ["Cobalt"]),
实现
扩展 Cobalt
类以在您的 API 客户端中使用。
初始化
import Cobalt
class APIClient: Cobalt.Client {
static let `default` = APIClient()
private init() {
let config = Cobalt.Config {
$0.authentication.clientID = "my_oauth_client_id"
$0.authentication.clientSecret = "my_oauth_client_secret"
$0.host = "https://api.domain.com"
}
super.init(config: config)
}
}
发送请求
APIClient 在内部使用 Google的Promises 来处理请求的响应
Promise
class APIClient: Cobalt.Client {
// ...
func users() -> Promise<[User]> {
let request = Cobalt.Request {
$0.path = "/users"
$0.parameters = [
"per_page": 10
]
}
return self.request(request).then { json: JSON -> Promise<[User]> in
let users = try json.map(to: [User].self)
return Promise(users)
}.catch { error in
print("Error: \(error)")
}
}
}
缓存
要启用磁盘缓存,请在Podfile中添加以下行
pod 'Cobalt/Cache'
然后像这样实现它
class APIClient: Cobalt.Client {
// ...
func users() -> Promise<[User]> {
let request = Cobalt.Request {
$0.path = "/users"
$0.cachingPolicy = .expires(seconds: 60 * 60 * 24) // expires after 1 day
}
return self.request(request).then { json: JSON -> Promise<[User]> in
let users = try json.map(to: [User].self)
return Promise(users)
}.catch { error in
print("Error: \(error)")
}
}
}
要清除整个缓存
APIClientInstance.cache.clearAll()
RxSwift
使用以下方法扩展上述类
import RxSwift
extension Reactive where Base: Cobalt.Client {
func users() -> Single<[User]> {
return self.users().asSingle()
}
}
然后像这样使用它
APIClient.default.rx.users() // ... rxswift etc.
常规闭包
不需要Promise或RxSwift,您也可以使用常规闭包
extension Promise {
func closure(_ handler: @escaping ((Value?, Error?) -> Void)) {
self.then { value in
handler(value, nil)
}.catch { error in
handler(nil, error)
}
}
}
然后像这样使用它
APIClient.default.users().closure { users, error
// ... Handle it
}
OAuth2
如果您想使用OAuth2协议登录用户,请使用Cobalt类的login()
函数。它将内部处理提供access_token
的检索和刷新
func login(email: String, password: String) -> Promise<Void>
您还可以使用其他认证方式
password
如果您想检索用户配置文件,需要.oauth2(.password)
身份验证,这样请求只有在用户通过login()
函数请求了访问令牌时才会成功。
如果访问令牌已过期,Cobalt会自动使用刷新令牌刷新它
class APIClient: Cobalt.Client {
// ...
func profile() -> Promise<User> {
let request = Cobalt.Request({
$0.authentication = .oauth2(.password)
$0.path = "/user/profile"
})
return request(request).then { json -> Promise<User> in
let user = try json["data"].map(to: User.self)
return Promise(user)
}
}
}
client_credentials
您必须为 Cobalt.Request
提供以下 .oauth2(.clientCredentials)
认证。
class APIClient: Cobalt.Client {
// ...
func register(email: String, password: String) -> Promise<Void> {
let request = Cobalt.Request({
$0.httpMethod = .post
$0.path = "/register"
$0.authentication = .oauth2(.clientCredentials)
$0.parameters = [
"email": email,
"password": password
]
})
return request(request).then { json -> Promise<Void> in
return Promise(())
}
}
这样 Cobalt 就会知道该请求需要一个带访问令牌的 client_credentials
grant_type。
如果用户已经有一个具有该 grant_type 的访问令牌,Cobalt 将使用它。如果没有,它将为您请求一个新的访问令牌。
清除 access_token
要将其从内存和密钥链中删除,请使用以下操作
func clearAccessToken()
开发
只需打开 Cobalt.xcodeproj