I try to manage rxswift & Alamofire to get response.
These functions get response successfully when token is not expired.
But when the token is expired, I don't know how to refresh token and then retry to get response using new token.
What should I do to refresh token and retry?
I also read Alamofire documents, and I find "RequestAdapter" and "RequestRetrier".
Should I use RequestAdapter & RequestRetrier in my case?
But I dont know how to use them in my "getRequestJSON" function,
or have any good idea to refresh token and retry.
Thanks.
func get(_ callback: @escaping (JSON) -> Void) {
let url = "http://106.xx.xxx.xxx/user"
self.getRequestJSON( .get, url: url, params: [:], callback: { json in
callback(json)
})
}
func getRequestJSON(_ method: Alamofire.HTTPMethod, url:String, params:[String:Any] = [:], callback: @escaping (JSON) -> Void) {
var headers:[String:String] = [String:String]()
if token.isEmpty == false {
headers["Authorization"] = "Bearer \(token)"
}
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
configuration.timeoutIntervalForRequest = timeout
_ = SessionManager(configuration: configuration)
.rx.responseJSON(method,
url,
parameters: params,
encoding: ((method == .get) ? URLEncoding.default : JSONEncoding.default),
headers: headers)
.subscribeOn(SerialDispatchQueueScheduler.init(qos: .background))
.subscribe(onNext: { (r, data) in
if r.statusCode == 401 {
//token fail
}
let json = JSON(data)
if json["status"].stringValue == "successful" {
callback(json)
}else {
callback(json)
}
}, onError: { (error) in
callback(JSON(error))
})
.addDisposableTo(ResfulAPIDisposeBag)
}