How to use NSURLConnection completionHandler with swift

一世执手 提交于 2019-11-30 01:55:28

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 */
})
Bluewings

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?.

sendAsynchronousRequest has been deprecated in newer versions of Swift. Move to dataTaskWithRequest, luckily it is used pretty much the same way

let request:NSURLRequest = NSURLRequest(URL:NSURL(string:"http://YOUR_DESIRED_URL.com")!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

});

task.resume()

The right term you are looking for here is Closure. Closures in Swift are similar to blocks in C and Objective-C. In addition to Tomáš's answer there is another short version to use the completion handler here:

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: {$0; $1; $2})

Here I have used Shorthand Argument Names. I am accessing response as $0, data as $1 and error as $3. I find this syntax more easy to read and write unless the parameters are large in number otherwise the code will become unreadable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!