我正在使用 Swift 5 开发 iOS 应用程序。 该应用使用 REST Api 从服务器获取一些数据,需要登录,并且应该使用不记名令牌来授权所有请求。
问题是所有请求仅在未设置 Bearer 令牌时才有效,即使它应该出现在所有请求的标头中。
我尝试手动设置它,但它不起作用。此外,尝试使用 Alamofire,但没有成功。即使是明确的 cookie 存储也没有让它起作用。
以下是我尝试的片段:
var myJwtToken = AppSettingsHelper.getSettings(key: AppStorageKey.tokenKey)
if myJwtToken != nil{
let bearerToken:String = "Bearer " + myJwtToken!
let headers: [String: String]? = [
"Accept": "application/json",
"Content-Type" : "application/json",
"Authorization": bearerToken
]
var urlComponents = URLComponents(string: myUrl)!
var request = URLRequest(url: urlComponents.url!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.method = .get
let cstorage = HTTPCookieStorage.shared
if let cookies = cstorage.cookies(for: request.url!) {
for cookie in cookies {
cstorage.deleteCookie(cookie)
}
}
AF.request(request).responseDecodable(of: MyObject.self, decoder: MyCustomDecoder()) { (response :AFDataResponse<MyObject>) in
do{
guard let validData = response.data else {
print("error on deserialization")
return
}
var jsonResult = try JSONSerialization.jsonObject(with: validData, options: [])
print(jsonResult)
}
catch let serializationError{
print(serializationError.localizedDescription)
}
}
第二次尝试,也不行
var myJwtToken = AppSettingsHelper.getSettings(key: AppStorageKey.tokenKey)
var request = URLRequest(url: myUrl)
request.httpMethod = .get
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer \(myJwtToken)", forHTTPHeaderField: "Authorization ")
对我做错了什么有任何想法或建议吗? 我得到的错误是:
Task .<1> 已完成错误 [303] Error Domain=kCFErrorDomainCFNetwork Code=303 "(null)" UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, _kCFStreamErrorDomainKey=4, NSErrorPeerAddressKey=