【发布时间】:2016-12-29 10:25:49
【问题描述】:
我正在开发一个需要大量使用 API 的 Swift 项目。一切正常,但有时(20 分之一),我在调用 API 时收到 Code=-1001 "The request timed out." 错误。
我正在使用 Alamofire。我附上调用 API 的代码。
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 15
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("\(myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)!.length)", forHTTPHeaderField: "Content-Length")
request.setValue("en-US", forHTTPHeaderField: "Content-Language")
Alamofire.request(request)
.validate()
.responseJSON { [weak self] response in
if response.result.isSuccess {
if let result = response.result.value {
print("Result: \(result)")
completion(result: result as! NSDictionary)
}
}
else {
print(response.debugDescription)
}
}
日志是
[Request]: <NSMutableURLRequest: 0x18855620> { URL: http://....... (url)}
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://.....(url) NSErrorFailingURLKey=http://.....(url), NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x18a08900 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}
[Timeline]: Timeline: { "Request Start Time": 493582123.103, "Initial Response Time": 493582138.254, "Request Completed Time": 493582138.254, "Serialization Completed Time": 493582138.256, "Latency": 15.151 secs, "Request Duration": 15.151 secs, "Serialization Duration": 0.002 secs, "Total Duration": 15.153 secs }
我知道我可以增加超时时间以避免错误。但我想知道它抛出错误的实际原因。我的 API 返回数据的时间都不超过 2 秒。那为什么它显示延迟为 15.151 秒。
我在后端使用 LAMP 堆栈。任何帮助将不胜感激。
【问题讨论】:
-
您是否看到在您的服务器上收到超时的请求?服务器处理它需要多长时间?
-
您每次访问的网址都完全相同吗?在我看来,这似乎不太可能是您的应用程序的问题。更有可能的是,您确实遇到过 API 很慢的情况。
-
@quant24 这就是问题所在。只有当我通过 iOS 设备点击它时它才会抛出这个错误。即使在 Android 上,一切正常。
-
@MikeTaverne 我每次都点击确切的 url 以检查错误是否已解决。但问题不是特定于一个 API。该错误会在应用程序中显示 iOS 设备上的任何 API。
-
我也遇到了同样的问题。问题是 API 命中永远不会到达后端,可能在发生网络切换或应用程序在 iOS 触发此请求之前进入后台时,就会发生这种情况。