Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NSURLConnection failed with Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." in Swift iOS8?

I use Xcode beta6. I created an app which have a Downloader class, and this is the Downloader class:

class Downloader : NSObject {

    private var _connection : NSURLConnection?
    private var _downloadedData: NSMutableData?

    func getDataFromURLString(urlToRequest: String!, aType: DownloadedDataType) {

        _downloadedData = NSMutableData()

        var request : NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlToRequest), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 20.0)
        request.setValue("", forHTTPHeaderField: "Accept-Encoding")

        self._connection = NSURLConnection(request: request, delegate:self)
    }

    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        println("Data expected size: \(response.expectedContentLength)")
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        println("finished")
    }

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        println("error: \(error)")
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!)  {
        _downloadedData?.appendData(data)
    }

}

This class works well and get the right JSON result when the server is on the network with LAN cable but when this server connected to the same network via WiFi I get this error from the iOS device:

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

But Its really weird because if I paste the json path to the browser I see the json.. So only on iOS devices cant handle, but I dont know what I should fix.. Can anyone help me?

So If my Mac mini what I use to develop is on Lan, and the Server is on Lan, everything works fine. But when my Mac mini is on WiFi and my server is on Wifi I get this error...

like image 900
szuniverse Avatar asked Sep 03 '14 19:09

szuniverse


1 Answers

Well, my first question is have you tried accomplishing the same task using the same logic/code in Objective-C / iOS 7? This would give us an idea if it's a problem in Swift, iOS 8, or a problem in your code. If you have, please post this code in an edit/update.

Second question: Why are you overriding the accept-encoding? Many servers require something there if you specify the header value. Best to remove that.

Third question: What version of iOS 8 beta are you running? FWIW, a simple search of SO showed this question: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

so it could be a bug in iOS 8 betas. I'd suggest trying objective-c first, and if that also breaks, goto the developer forums and post your issue to get Apple's attention on it. You might also want to open a Radar for it.

like image 150
Matt S. Avatar answered Sep 19 '22 08:09

Matt S.