更新到xcode8 Alamofire4后,我的AlamofireRequest无效,在请求中返回“状态代码:401,标题”(未授权)。用户授权是正确的(我已检查过该站点)。我没有任何编译器错误,但请注意“标题”不像往常一样以蓝色突出显示,因此我认为它无法正确识别标题。我在这里对'标题'做错了吗?
let user = "sampleUser"
let password = "samplepass"
let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]
var checkUserEndpoint: String = "https://sample.com/ios1/user/\(uidEntered!).json"
print(checkUserEndpoint)
Alamofire.request(checkUserEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
我已经尝试过使用它代替标题,但它没有区别:
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
我也试过这个并没有什么区别;
Alamofire.request(checkUserEndpoint,
method: .get,
parameters: nil,
encoding: JSONEncoding.default)
.authenticate(user: "sampleUser", password: "samplepass")
.validate()
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
// print(response.error)
答案 0 :(得分:1)
我已经完成了两次类似的迁移,而且我有根据的猜测是,你传递给生成标题值的一个字符串是可选的,即。 password
,base64Credentials
或if let user = user, password = password, base64Credentials = base64Credentials {
let headers = ["Authorization": "Basic \(base64Credentials)"]
var checkUserEndpoint: String = "https://sample.com/ios1/user/\(uidEntered!).json"
print(checkUserEndpoint)
Alamofire.request(checkUserEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
}
;虽然生成可选(" thestring")而不是" thestring"。你可以试着像这样包装请求:
nonnull
这可能发生在例如。在某种情况下,这些值来自Objective-C代码,其中变量未标记为base64Credentials
。
... {{1}}不应该是可选的,如文档中所述。
答案 1 :(得分:0)
两种变体中的代码都是正确的(手动标题创建和Alamofire请求.authenticate用法)。看起来像服务器端问题,使用curl / postman或任何其他REST客户端在继续开发应用程序之前从服务器接收成功响应。