所以我试图在每次请求之前检查承载是否有效,但是当我运行刷新令牌请求时,Alamofire 在调度前提条件下得到一个异常:我做错了什么?这甚至可能吗?
extension Session: SessionStateProvider {
func request(for task: URLSessionTask) -> Request? {
dispatchPrecondition(condition: .onQueue(rootQueue))
return requestTaskMap[task]
}
首先检查令牌的请求的主要调用者
private static func createRequest(urlConvertible: URLRequestConvertible)-> Alamofire.DataRequest?{
if let manager = sessionManager{
return manager.request(urlConvertible)
///custom manager that checks the tokens
}else if let manager = authenticatedManager{
manager.verifyRequest(url: urlConvertible) { (result) in
return result
}
}
return nil
}
/// This method make a request using the JSONAPI's Format - Only to the 'data' structure
///
/// - Parameter urlConvertible: Codabel Onject to parse teh response
/// - Returns: The Codable object if success or not
static func requestJSONAPI<T: Codable> (_ urlConvertible: URLRequestConvertible) -> Observable<T> {
initManager(urlConvertible: urlConvertible)
//Create an RxSwift observable, which will be the one to call the request when subscribed to
return Observable<T>.create { observer in
let request = createRequest(urlConvertible: urlConvertible)?
.debugLog()
.validate()
.responseCodableJSONAPI(keyPath: "data", completionHandler: { (response: AFDataResponse<T>) in
switch response.result {
case .success(let value):
let jsonDataString = String(data: response.data ?? Data(), encoding: String.Encoding.utf8)!
print("Post Request Params : \(jsonDataString)")
observer.onNext(value)
这是我的代码,其中 auth.refreshtokens 使用 AF.request 获取新令牌
private func shouldRefreshToken() -> Bool {
do {
let jwt = try decode(jwt: accessToken)
return jwt.expired
} catch {
}
return false
}
func verifyRequest(url: URLRequestConvertible, completion: @escaping (_ result: DataRequest) -> Void){
if shouldRefreshToken() {
let auth = interceptor
///makes an AF.request to get the new tokens - where it crashes
auth.refreshTokens { [weak self] succeeded, accessToken, refreshToken in
self?.accessToken = accessToken!
completion((self?.sessionManager?.request(url))!)
}
}else{
completion((self.sessionManager?.request(url))!)
}
}
´´´