我想使用 JWT解码和 alamofire 使用刷新令牌来刷新令牌。 我将令牌和刷新令牌保存在应用默认设置中! 一切正常,日志过程正常,但是我的问题是我不知道如何刷新过期的令牌。
import Foundation
import Alamofire
import SwiftyJSON
import JWTDecode
class AuthService {
static let instance = AuthService()
var controller = UIViewController()
let defaults = UserDefaults.standard
var isLoggedIn : Bool {
get {
return defaults.bool(forKey: LOGGED_IN_KEY)
}
set {
defaults.set(newValue, forKey: LOGGED_IN_KEY)
}
}
var authToken: String {
get {
let str = UserDefaults.standard.object(forKey: TOKEN_KEY) as? String
return str == nil ? "" : str!
}
set {
defaults.set(newValue, forKey: TOKEN_KEY)
}
}
var refreshToken: String {
get {
return defaults.value(forKey: REFRESH_KEY) as! String
}
set {
defaults.set(newValue, forKey: REFRESH_KEY)
}
}
var message: String {
get {
return defaults.value(forKey: MESSAGE) as! String
}
set {
defaults.set(newValue, forKey: MESSAGE)
}
}
var error: String {
get {
let strError = UserDefaults.standard.object(forKey: ERROR) as? String
return strError == nil ? "" : strError!
//return defaults.value(forKey: ERROR) as! String
}
set {
defaults.set(newValue, forKey: ERROR)
}
}
var errorEmail: String {
get {
let strErrorEmail = UserDefaults.standard.object(forKey: ERROREMAIL) as? String
return strErrorEmail == nil ? "" : strErrorEmail!
}
set {
defaults.set(newValue, forKey: ERROREMAIL)
}
}
func loginUser(email: String, password: String, complition: @escaping CompletionHandler) {
let lowerCaseEmail = email.lowercased()
let body: [String: Any] = [
"email": lowerCaseEmail,
"password": password
]
Alamofire.request(URL_LOGIN, method: .post, parameters: body, encoding: JSONEncoding.default, headers: BEARER_HEADER).responseJSON { (response) in
if response.result.error == nil {
//Using SwiftyJSON
guard let data = response.data else { return }
let json = try! JSON(data: data)
self.authToken = json["data"]["data"]["token"].stringValue
self.refreshToken = json["data"]["data"]["refresh"].stringValue
self.message = json["message"].stringValue
self.error = json["error"].stringValue
print(self.error)
self.isLoggedIn = true
complition(true)
let jwt = try? decode(jwt: self.authToken)
if jwt != nil {
let userInfo = jwt!.body["data"] as? [String: Any]
let userInfo2 = userInfo!["user"] as? [String: Any]
let country_code = userInfo2!["country_code"]
print(country_code!)
} else {
ErrorAthService.instance.errorUser(email: lowerCaseEmail, password: password)
}
} else {
complition(false)
debugPrint(response.result.error as Any)
}
}
}
}