使用SwiftyBeaver记录器时出现此错误,该记录器尝试通过此代码将数据发送到云端:
func sendToServerAsync(str: String?, complete: (ok: Bool, status: Int) -> ()) {
if let payload = str, let queue = self.queue {
// create operation queue which uses current serial queue of destination
let operationQueue = NSOperationQueue()
operationQueue.underlyingQueue = queue
let session = NSURLSession(configuration:
NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: nil, delegateQueue: operationQueue)
// assemble request
let request = NSMutableURLRequest(URL: serverURL)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// basic auth header
let credentials = "\(appID):\(appSecret)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentials.base64EncodedStringWithOptions([])
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
// POST parameters
let params = ["payload": payload]
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch let error as NSError {
toNSLog("Error! Could not create JSON for server payload. \(error)")
}
//toNSLog("sending params: \(params)")
//toNSLog("\n\nbefore sendToServer on thread '\(threadName())'")
sendingInProgress = true
// send request async to server on destination queue
let task = session.dataTaskWithRequest(request) {
_, response, error in
var ok = false
var status = 0
//toNSLog("callback of sendToServer on thread '\(self.threadName())'")
if let error = error {
// an error did occur
self.toNSLog("Error! Could not send entries to server. \(error)")
} else {
if let response = response as? NSHTTPURLResponse {
status = response.statusCode
if status == 200 {
// all went well, entries were uploaded to server
ok = true
} else {
// status code was not 200
var msg = "Error! Sending entries to server failed "
msg += "with status code \(status)"
self.toNSLog(msg)
}
}
}
return complete(ok: ok, status: status)
}
task.resume()
}
}
奇怪的是它适用于前两个或三个日志条目,然后由于上述错误而停止。我尝试重置模拟器上的内容和设置并重新启动我的模拟器(如Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."中所述),但只是暂时修复它 - 在前2-3个日志条目之后,它再次开始失败。
我昨晚尝试使用SwiftBeaver的创建者调试了几个小时,但是我们无法让它工作。似乎没有多少人看到这个问题。
我尝试删除我的Wifi连接并重新连接,但这也没有用。
对此的任何指导都将非常感激。
仅供参考,我使用的是Swift 2和XCode 7.3。
答案 0 :(得分:1)
这可能是由于iOS保持活动支持在iOS模拟器中严重错误造成的。参见:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
有关更多详细信息,但简短的回答是在执行模拟器测试时使用的服务器上禁用keep-alive,或者更好的是,添加一些在遇到特定错误时立即重试请求的逻辑。