RxMoyaAuthenticatable
使用RxMoyaAuthenticatable让你的API token 可刷新!
RxMoyaAuthenticatable提供标准的requestClosure,可以根据你的需要自动刷新accessToken!
This requestClosure拦截你的请求,执行以下操作
- 在串行dispatch queue中挂起所有请求,
- 找到持久的身份验证,
- 如需则刷新发现的身份验证,
- 在串行队列中恢复其他请求。
如何使用
适应你的Authentication
实体到RefreshableAuthentication
协议
public protocol RefreshableAuthentication {
var isRefreshNeeded: Bool { get }
var accessToken: String { get }
func refresh() -> Single<Self>
static func find() -> Self?
}
例如
import RxSwift
import Moya
import RxMoyaAuthenticatable
struct SpotifyAuthentication: RefreshableAuthentication, Decodable {
let accessToken: String
var refreshToken: String!
var createdAt: Date = Date()
let expiresIn: Int
var isRefreshNeeded: Bool {
let threshold = TimeInterval(self.expiresIn / 2)
let result = self.expiresAt < Date().addingTimeInterval(threshold)
return result
}
static func find() -> SpotifyAuthentication? {
return SpotifyAuthenticationStore.find()
}
func refresh() -> Single<SpotifyAuthentication> {
let refreshToken = self.refreshToken
return
SpotifyAuthAPI
.sharedProvider
.rx
.request(.refreshToken(refreshToken: self.refreshToken))
.map { response -> SpotifyAuthentication in
if var authentication = try? JSONDecoder().decode(SpotifyAuthentication.self, from: response.data) {
authentication.refreshToken = refreshToken
return authentication
} else {
throw SpotifyAPIError.mappingError
}
}.do(
onSuccess: { authentication in
SpotifyAuthenticationStore.save(authentication: authentication)
},
onError: { error in
print(error)
}
)
}
}
extension SpotifyAuthentication {
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case refreshToken = "refresh_token"
case expiresIn = "expires_in"
}
var expiresAt: Date {
return createdAt.addingTimeInterval(TimeInterval(expiresIn))
}
}
(详见使用Spotify API的示例实现此处)
使用此协议和您的API,当isRefreshNeeded
返回True时,accessToken将自动刷新
let provider = MoyaProvider<SpotifyAPI>(
requestClosure: RxMoyaAuthenticatable<SpotifyAPI, SpotifyAuthentication>().requestClosure
)
示例
要运行示例项目,请克隆仓库,查看Example/Readme.md。在这个示例中,我们实现了Spotify的授权码流。
要求
目标 | 版本 |
---|---|
苹果iOS | => 11.0 |
Swift语言 | => 4.0 |
Moya/RxSwift框架 | => 11.0 |
安装
RxMoyaAuthenticatable可以通过CocoaPods或者Carthage获得。
CocoaPods
pod 'RxMoyaAuthenticatable'
Carthage
github "Moya/Moya"
github "keitaoouchi/RxMoyaAuthenticatable"
作者
keitaoouchi, [email protected]
许可证
RxMoyaAuthenticatable可以在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。