MrSSS16 MrSSS16 - 1 year ago 96
Swift Question

Swift can't send URLRequest at all?

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

Answer Source

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. See http://stackoverflow.com/questions/30702387/using-nsurlsession-from-a-swift-command-line-program/40870157#40870157 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download