我正在Swift 2.0的iOS项目中工作,该项目有Web服务调用,这些服务响应缓慢,这是正常的,可能长达1分钟或更长时间,当我调用服务时,70%的时间它会回答错误“网络连接丢失”。测试在模拟器、不同的手机设备和iPad上进行,结果是一样的。网络连接很强,同样的应用程序也是在Android上创建的,几乎100%的时间都能正常工作。
我从任何角度调用服务的方式如下:
@IBAction func contratarAct(sender: AnyObject) {
conexion.delegate = self
loadingView = MEXLoadingView(delegate: self, title: "Espere por favor", percent: false, view: self.view)
self.loadingView.showAnimated(true)
let url = urlServicios.urlBaseServicios + "/" + idSolicitud + "/" + idNoCliente + "/CONTRATO"
conexion.consultaServicioGET(url, httpMethod: "PUT")
}
并且所执行的方法如下:
func consultaServicioGET(url : String, httpMethod : String ){
let urlString = url
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.timeoutInterval = 540
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
var session = NSURLSession.sharedSession()
request.HTTPMethod = httpMethod
let urlconfig = NSURLSessionConfiguration.defaultSessionConfiguration()
urlconfig.timeoutIntervalForRequest = 540
urlconfig.timeoutIntervalForResource = 540
session = NSURLSession(configuration: urlconfig, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request , completionHandler: {
(data:NSData?, response:NSURLResponse?, error:NSError?) in
if error != nil {
let jsonError : NSDictionary = NSDictionary()
self.delegate?.respuestaServicioGET!(jsonError, mensaje: "\(error!.localizedDescription)")
return
}
let jsonString = NSString(data: data!,encoding: NSASCIIStringEncoding)
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
let json: NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if (json.isKindOfClass(NSDictionary) ){
self.delegate?.respuestaServicioGET!(json, mensaje: "OK")
}else{
let jsonError : NSDictionary = NSDictionary()
self.delegate?.respuestaServicioGET!(jsonError, mensaje: "ERROR")
}
})
task.resume()
}
显示的错误是:
错误=可选(错误域=NSURLErrorDomain Code=-1005"网络连接丢失。"UserInfo={NSUnderlyingError=0x7fbde5f51df0{错误域=kCFErrorDomainCFNetwork Code=-1005"(null)"UserInfo={_kCFStreamErrorCodeKey=-4,_kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://particulares-gw-obparticularesmx-pre.appls.cto2.paas.gsnetcloud.com:443/OPB/57dadf7de4b0ac2e518de44a/57dadf7de4b06c6b04ef0dcf/CONTRATO, NSErrorFailingURLKey=https://particulares-gw-obparticularesmx-pre.appls.cto2.paas.gsnetcloud.com:443/OPB/57dadf7de4b0ac2e518de44a/57dadf7de4b06c6b04ef0dcf/CONTRATO,_kCFStreamErrorDomainKey=4,_kCFStreamErrorCodeKey=-4, NSLocalized描述=网络连接丢失。})
我添加了如下代码:
urlconfig.timeoutIntervalForRequest=540urlconfig.timeoutIntervalForResources=540
试图获得更多的“超时”,但这看起来不像超时。
我无法摆脱这个错误好几天,任何帮助将不胜感激。我很绝望。
如果你希望一个插座一次保持打开几分钟,你就会受到伤害。这可能适用于Wi-Fi,但在蜂窝网络上,由于塔切换或其他一些你无法控制的随机事件,连接故障的可能性很高。当这种情况发生时,连接断开,你的应用程序对此无能为力。
这确实需要通过改变客户端请求数据的方式来解决,以便响应更加异步。明确地:
使用该模型,与服务器的连接是否关闭并不重要,因为后续请求将成功获取数据。
我遇到了同样的问题,我附上了解决方案的截图,以显示我是如何解决这个问题的。
在我的情况下,问题是API请求被服务器Sucuri/CloudAgent阻止(或者你可以说防火墙服务)。禁用防火墙解决了这个问题
我不知道为什么,但当我在请求之前添加睡眠时,它是有效的:
sleep(10000)
AF.request(ViewController.URL_SYSTEM+"/rest,get_profile", method: .post, parameters: params, encoding: JSONEncoding.default , headers: headers).responseJSON { (response) in
}