1

No matter what I do it seems I'm unsuccessful in sending requests. Given the below sample code I copied word for word just to see the results. Yet nothing happens, I'm really confused and need help figuring out why i can send requests fine with objective c but no matter how many variations NSURLRequest NSURLSession I try it never works on swift.

var url : String = "http://google.com?test=toto&test2=titi"

var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),

    completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

        if (jsonResult != nil) {
            println("help me")
            // process jsonResult
        } else {
            println("hmmm")
            // couldn't load JSON, look at error
        }
})
Wain
  • 118,658
  • 15
  • 128
  • 151
MrSSS16
  • 449
  • 3
  • 7
  • 21
  • Your comment in the code says you're going to look at the error object. Did you? You don't appear to look at any of the return codes to see if you had an error, and if so, what that error was. I suspect that you're trying to parse JSON from an `NSData` that won't contain JSON. Try looking at a string representation the data object, e.g. `println(String(data: data, encoding: NSUTF8StringEncoding))`. (And of course, check to see if either of your `NSError` objects were non-`nil`, and if so, print them, too. – Rob Dec 31 '14 at 10:55
  • In the simulator or on a device? – Wain Dec 31 '14 at 11:00
  • @Wain I'm not using it on a simulator its just as a command line tool project. And I check `if(error != nill)` it never gets to that line or anything after it. – MrSSS16 Dec 31 '14 at 11:08
  • Which error? The connection error thT you are masking or the JSON error? Have you debugged and checked breakpoint hits? – Wain Dec 31 '14 at 11:10

2 Answers2

4

DO NOT test network asynchronous requests on a commande line project. The execution flow will stop before the asynchronousRequest terminates... You would need to add a run loop for that. Check out this link for an example.

You should take the habit to print out everything you get from a request, to understand what is going on. You can comment out everything after you are sure the request is working as expected.

var url : String = "http://google.com?test=toto&test2=titi"

var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),

    completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        println("OK")

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

        println("Body: \(strData)\n\n")
        println("Response: \(response)")

        var err:NSError?
        let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary

        if (jsonResult != nil) {
            println("jsonresult : \(jsonResult)")
            // process jsonResult
        } else {
            println(err.debugDescription)
            // couldn't load JSON, look at error
        }
})

I added a line to print the NSData converted to a NSString. Here the data is nil.

That explains the JSON parsing error.

Also, the way you create the error is not right. Check out my version to correct it.

Community
  • 1
  • 1
Mehdi.Sqalli
  • 510
  • 1
  • 5
  • 22
1

You aren't checking for the results of your various variables. If you're trying to diagnose problems, you have to look at each critical variable. For example, first check to see if the request succeeded and if not, quit immediately. Otherwise, try parsing the JSON, showing the resulting object if successful, but showing the parsing error on failure. If the JSON parsing fails (as it will with this URL), you might even look at the string representation of the returned data.

FYI, the handling of the NSError object with NSJSONSerialization is also incorrect. It should look like:

var parsingError: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parsingError) as? NSDictionary {
    // success, use `jsonResult`
} else {
    // failure, look at `parsingError`
}

Putting that all together:

let url = "http://google.com?test=toto&test2=titi"

let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "GET"

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

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

    var parsingError: NSError?
    if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parsingError) as? NSDictionary {
        println("json parsed: \(jsonResult)")
    } else {
        println("parsing error: \(parsingError)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("data: \(responseString)")
    }
}

This will, with this particular URL, fail, because the response is not JSON, but this will also show you the string representation of the response.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks, but unfortunately still no response...when I debug and step through each line it gets to the `sendAsynchronousRequest` call then the progam ends. Dare I say it maybe its an issue with my particular `swift` release. Because I have had others run code similar to mine and it runs 'as expected' where as it doesn't work on mine. – MrSSS16 Dec 31 '14 at 11:28
  • It is unlikely to be your "particular Swift release". What version of Xcode are you using? Having said that, sometimes (though rarely) Xcode gets in an unstable state and restarting Xcode (or even rebooting Mac) helps. So, try restarting your Mac. More likely, though, this is a simple crash of the app, not Swift/Xcode. You have to clarify "then the program ends". If app crashes, if there is anything shown in Xcode's console, you should edit your question and show us what it says. – Rob Dec 31 '14 at 11:33
  • Ok so after `sendAsynchronousRequest` is called the console just displays `Program ended with exit code: 0` I don't get any other messages. – MrSSS16 Dec 31 '14 at 11:41