我正在尝试将承载令牌添加到URLrequest中,但不幸的是,该请求为nil,我不知道自己是否以正确的方式进行操作,但目前无法正常工作。 我的意图是添加用户令牌或匿名令牌,这取决于两点:
这些是我想包括的3种可能性,用于填写URLrequest,但是当我
print(“ request(request.allHTTPHeaderFields)”)
控制台中的结果为
request可选([:])
我该怎么做才能获得理想的结果?
public static var fake: Resource<[User]> = Resource(request: { (url) -> URLRequest in
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
components.path = "/dev/fake-users"
var request = URLRequest(url: components.url!)
request.httpMethod = "GET"
if let token = SessionProvider().getUserToken(){
SessionController().refreshToken(refreshToken: (SessionProvider().getUserToken()?.refreshToken)!, completion: { (error) in
if let error = error{
if let anonymousToken = SessionProvider().getAnonymousToken(){
request.setValue("Bearer \(anonymousToken)", forHTTPHeaderField: "Authorization")
}
}else{
request.setValue("Bearer \(token.accessToken)", forHTTPHeaderField: "Authorization")
}
})
}
else if let anonymousToken = SessionProvider().getAnonymousToken(){
request.setValue("Bearer \(anonymousToken)", forHTTPHeaderField: "Authorization")
}
print("request \(request.allHTTPHeaderFields)")
return request
}) { (data) -> [User] in
let unboxer = Unboxer(dictionary: data as! UnboxableDictionary)
return try unboxer.unbox(key: "hits")
}
现在刷新令牌功能
public static func refreshToken(refreshToken: String) -> Resource<String> {
return Resource(request: { (url) -> URLRequest in
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
components.path = "/v1/oauth/login"
var request = URLRequest(url: components.url!)
request.httpMethod = "POST"
request.setValue("Basic \(Keys.basic)", forHTTPHeaderField: "Authorization")
request.setValue(SessionProvider().getInstanceToken(), forHTTPHeaderField: "x-bok-instance")
var dictionary: [String: Any] = [:]
dictionary["refreshToken"] = refreshToken
dictionary["grantType"] = "refresh_token"
request.httpBody = try? JSONSerialization.data(withJSONObject: dictionary, options: [])
return request
}, dataParser: { data -> String in
let unboxer = try Unboxer(data: data)
return try Unboxer(data: data).unbox(key: "accessToken")
})
}