我想检索请求失败的HTTP响应状态代码(例如400,401,403,503等)(理想情况下也是成功的).在此代码中,我使用HTTP Basic执行用户身份验证,并希望能够在用户输错密码时向用户发送身份验证失败的消息.
Alamofire.request(.GET, "https://host.com/a/path").authenticate(user: "user", password: "typo")
.responseString { (req, res, data, error) in
if error != nil {
println("STRING Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for String")
}
.responseJSON { (req, res, data, error) in
if error != nil {
println("JSON Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for JSON")
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,产生的错误似乎并不表示实际收到了HTTP状态代码409:
STRING Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
res:nil
data:Optional("") …Run Code Online (Sandbox Code Playgroud) 我试图通过https为我的iOS应用程序使用Web服务.Web服务器使用自签名证书.
在使用Web服务时,我收到错误"证书无效".
FAILURE:Error Domain = NSURLErrorDomain Code = -1202"此服务器的证书无效.您可能正在连接到假装为"门户"的服务器,这可能会使您的机密信息面临风险."
我知道最佳做法是在服务器端修复此问题以启用受信任的根CA. 但由于这是一个临时开发环境,我们使用自签名证书.由于这是ATS问题,我在info.plist中编辑了ATS,如下所示.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>devportal</key>
<dict>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)
由于NSException域不能与IP和端口号一起使用,我在我的etc/hosts文件中为Web服务器IP创建了一个主机条目,并像https:// devportal:8443/rest/login一样使用它而不是消耗它如https://192.22.xx.xxx:8443/rest/login
我已经关注了服务器信任策略的alamofire文档,编辑了ATS以允许异常域,但没有任何解决方案.我在这个问题上花了3天多的时间.我错过了什么吗?有人遇到过类似的问题吗?这有什么解决方案吗?提前致谢
我正在使用almofire 4.0,Xcode 8.0.以下是我的代码.
class LoginService{
private static var Manager: Alamofire.SessionManager = {
let pathToCert = Bundle.main.path(forResource: "192.22.xx.xxx", ofType: "crt") // Downloaded this certificate and have added to my bundle
let localCertificate:NSData = …Run Code Online (Sandbox Code Playgroud)