- (NSURLSessionTask *)authenticateUsingOAuthWithURLString:(NSString *)URLString
refreshToken:(NSString *)refreshToken
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure;
使用此方法,您可以向身份验证服务器提供新的 refreshToken。在此之前,您需要在用户默认值中将 AFOAuthCredential保存为 NSData,然后在调用 api 时检索 AFOAuthCredential 并使用此方法检查它是否已过期。
func refreshTokenIfUnavailable(completionHandler : @escaping(_ finished:Bool,_ error:Error) -> ()) {
let credentialData = UserDefaults.standard.object(forKey: CREDENTIAL) as? NSData
if let credentialData = credentialData {
let credential = NSKeyedUnarchiver.unarchiveObject(with: credentialData as Data) as? AFOAuthCredential
if let _ = credential
{
if credential!.isExpired {
let urlString = OAUTH_BASE_URL
let url = URL(string: urlString)
let oAuthManager = AFOAuth2Manager(baseURL: url!, clientID: YOUR_AUTH_CLIENT_ID secret: YOUR_AUTH_SECRET_ID)
oAuthManager.authenticateUsingOAuth(withURLString: "oauth/token", refreshToken: (credential?.refreshToken)!, success: { (credential) in
self.saveAccessToken(credential: credential)
completionHandler(true,YOUR_ERROR))
}, failure: { (error) in
completionHandler((credential != nil),NSError(domain: "", code: 204, userInfo: [NSLocalizedDescriptionKey: error.localizedDescription]))
})
}
completionHandler((credential != nil),YOUR_ERROR_MESSAGE))
}
}
}
func saveAccessToken(credential : AFOAuthCredential) {
KeychainService.saveAccessToken(service: ACCESS_TOKEN as NSString, data: credential.accessToken as NSString)
let credentialData = NSKeyedArchiver.archivedData(withRootObject: credential)
let userDefaults = UserDefaults.standard
userDefaults.set(credentialData, forKey: "credentials")
}
希望这个能满足你的需要。快乐编码:)