1

I am trying to build a really basic iOS app using Swift - this is my first time doing so. Whilst the majority of it has been really straight forward. I have had a total nightmare getting the app to talk to my API, or any site in general!

This is the code i'm using, and specifically the code which is erroring:

     NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{     (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
         println(NSString(data: data, encoding: NSUTF8StringEncoding))
     })

it's the 'NSString(data: data, encoding: NSUTF8StringEncoding)' that errors

I've gone through as many tutorials as I can find, and they all return me the same problem. I get an error saying:

NSURLErrorDomain - code: 4294966291

I also get a 'EXC_BAD_INSTRUCTION' error with: EXC_1386_INVOP, sub code = 0x0 (which hasn't led me to a solution...

Which makes me think that I haven't done something right in my set up, or something should be turned on in my preferences, or something along those lines as opposed to my code...

this is my whole code:

    var URL: NSURL = NSURL(string: "http://stackoverflow.com")

    var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
    request.HTTPMethod = "POST"

    var bodyData = "key1=value&key2=value&key3=value"

    println(URL)
    println(bodyData)

    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    })

Update:

Using Rob's code, I know get an error printed:

sendAsynchronousRequest error: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo=0x7beafcc0 {NSErrorFailingURLStringKey=http://stackoverflow.com, _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey=http://stackoverflow.com, NSLocalizedDescription=The network connection was lost., _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7d154ca0 "The network connection was lost."}

Rob
  • 415,655
  • 72
  • 787
  • 1,044
user2707631
  • 286
  • 3
  • 6
  • Did you change the URL before posting this? The above works for me. I'd always set `Content-Type`, e.g. `request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")`, but I don't think that's the problem here. – Rob Oct 08 '14 at 14:23
  • This is literally the code I have! – user2707631 Oct 08 '14 at 14:29
  • I would next run this with [Charles](http://charlesproxy.com) and see what the response looks like. – Rob Oct 08 '14 at 14:41
  • I might also suggest trying with different URL (to see if problem is Stack Overflow server's response). Bottom line, other than missing error handling (which you've obviously now added) and missing `Content-Type`, I don't see any problems with the above code. And it's hard to diagnose if we can't reproduce the problem. – Rob Oct 08 '14 at 15:05

2 Answers2

2

It sounds like data is nil. Examine the contents of the error object, and it should give you an indication of why. Most likely, there's something wrong with the request, but unless we can reproduce the problem, it's hard to diagnose.

Anyway, if you want to perform the request with a little more diagnostic information (log error if there is a problem, log statusCode and response if status code was not 200, etc.):

NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
    response, data, error in

    if data == nil {
        println("sendAsynchronousRequest error: \(error)")
        return
    }

    if let httpResponse = response as? NSHTTPURLResponse {
        let statusCode = httpResponse.statusCode
        if statusCode != 200 {
            println("sendAsynchronousRequest status code = \(statusCode); response = \(response)")
        }
    }

    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

In your revised question, you shared the resulting NSError, which reported -1005 (which, in retrospect, is the same as the 4294966291 error code you showed us earlier; the latter being the the unsigned integer representation of -1005). This error (as the description describes) is for NSURLErrorNetworkConnectionLost (which is kCFURLErrorNetworkConnectionLost), for which the documentation says, "Returned when a client or server connection is severed in the middle of an in-progress load."

Unfortunately, this error is used for a diverse array of issues, and as I'm unable to reproduce the error you describe, it's hard to diagnose.


One thing that is missing from the request is the specification of the Content-Type:

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

That wouldn't cause the problem you describe, but it's good practice to always inform the server of the type of the request.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
1

I solved this, partly thanks to Rob's answers and general help - that was very useful.

The Key in the end though, was super simple and taken from this question: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

I just had to restart the simulator. However I wouldn't have gotten there without the additional if data == nil {} statement.

Community
  • 1
  • 1
user2707631
  • 286
  • 3
  • 6