0

I am getting this error when using SwiftyBeaver logger, which tries to send data to the cloud via this code:

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()
        }
    }

The strange thing is it works for the first two or three log entries, and then stops due to the above error. I tried to reset content and settings on the simulator and reboot my simulator (as suggested in Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost.") but that just fixes it temporarily--after the first 2-3 log entries, it starts failing again.

I tried debugging this for hours with the creator of SwiftBeaver last night, but we couldn't get it to work. Seems like not many people are seeing this issue.

I tried removing my Wifi connection and reconnecting, but that didn't work either.

Any guidance on this would be much appreciated.

FYI, I'm using Swift 2 and XCode 7.3.

Community
  • 1
  • 1
Prabhu
  • 12,995
  • 33
  • 127
  • 210

1 Answers1

1

This is probably caused by HTTP keep-alive support being seriously buggy in the iOS simulator. See:

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

for more details, but the short answer is to disable keep-alive on the server that you use when doing simulator testing, or better yet, add some logic that immediately retries the request if it sees that particular error.

Community
  • 1
  • 1
dgatwood
  • 10,129
  • 1
  • 28
  • 49