Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSURLConnection completionHandler with swift

Does anybody know how handlers (blocks) work in swift? I am trying to get this code running but i can't find any documentation of the right syntax for the completionHandler.

let url:NSURL = NSURL(string:"some url")
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request:request, queue:queue, completionHandler handler:((NSURLResponse!, NSData!, NSError!) -> Void)!)
like image 724
loopmasta Avatar asked Jun 03 '14 13:06

loopmasta


2 Answers

Like this:

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ response, data, error in /* Your code */ })

Or more verbose variant.

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    /* Your code */
})
like image 170
Tomáš Linhart Avatar answered Oct 20 '22 00:10

Tomáš Linhart


You need to use this code:

NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in /* code goes here */ })

For more info, you can refer to this tutorial, or or check the answers to How to parse a JSON file in swift?.

like image 29
Bluewings Avatar answered Oct 20 '22 01:10

Bluewings