我有一个非常简单的设置。
如果我检查了request.request
中的retry()
,则没有在adapt()
中添加的标题
实际上..我不知道为什么它进入retry()
的状态为401状态,当我知道我“附加”的Bearer令牌有效的事实时,我甚至将该令牌硬编码在Adapt()中,而不是从UserDefaults获取它。
import Foundation
import Alamofire
class OAuthInterceptor: RequestInterceptor {
private var clientKeys: ClientKeys
private var baseURLString: String
// MARK: - Initialization
public init(clientKeys: ClientKeys, baseURLString: String) {
self.clientKeys = clientKeys
self.baseURLString = baseURLString
}
// MARK: - RequestAdapter
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (AFResult<URLRequest>) -> Void) {
if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix(baseURLString) {
var adaptedRequest = urlRequest
if let sToken = UserDefaults.standard.string(forKey: "SP_TOKEN") {
//it doesnt work even if I hardcode the token
adaptedRequest.setValue("Bearer \(sToken)", forHTTPHeaderField: "Authorization")
print("? >> AuthToken appended: \(urlString)")
}else{
print("?❌ >> No Token appended: \(urlString)")
}
//If I inspect the adaptedRequest right here.. it DOES have the Headers, if it went thru the right conditional above.
completion(.success(adaptedRequest))
}
completion(.success(urlRequest))
}
// MARK: - RequestRetrier
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
//print(request.request) this will show No Headers added at all, so then what happened in adapt()
completion(.doNotRetry)
}
}
单人班
import Foundation
import Alamofire
fileprivate let SP_CLIENT_ID:String = "doesnt matter"
fileprivate let SP_CLIENT_SECRET: String = "doesnt matter"
struct ClientKeys{
var id:String?
var secret:String?
}
class SpotifyAPI: NSObject {
static let shared = SpotifyAPI()
static let baseUrl: String = "https://api.spotify.com/v1"
var mainSession: Session!
private override init(){
let clientKeys = ClientKeys(id: SP_CLIENT_ID, secret: SP_CLIENT_SECRET)
let configuration = URLSessionConfiguration.default
mainSession = Session(configuration: configuration, interceptor: OAuthInterceptor(clientKeys: clientKeys, baseURLString: SpotifyAPI.baseUrl))
}
func playlistFromG8(){
mainSession.request("\(SpotifyAPI.baseUrl)/users/12100663099/playlists").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON { response in
switch response.result{
case .failure(let f):
//It always fails with 401
print(">> ERROR:",f)
case .success(let s):
print(">> SUCCESS: ",s)
}
}
}
}
只需致电SpotifyAPI.shared.playlistFromG8()
在retry()中,我设置了一个断点
po request.request
▿ Optional<URLRequest>
▿ some : https://api.spotify.com/v1/users/12100663099/playlists
▿ url : Optional<URL>
▿ some : https://api.spotify.com/v1/users/12100663099/playlists
- _url : https://api.spotify.com/v1/users/12100663099/playlists
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __C.NSURLRequestNetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
这里是一个演示项目:https://github.com/omarojo/AFInterceptorDemo
Alamofire Github问题:https://github.com/Alamofire/Alamofire/issues/2877