How to use NSURLSessionDataTask in Swift
It's unclear what you're asking, but I noticed that you have a couple of errors in the code:
You should create your
session
usingNSURLSession(configuration: config)
session.dataTaskWithRequest
returns aNSURLSessionDataTask
, so there's no need to wrap it insideNSURLSessionDataTask()
(a.k.a instantiating a newNSURLSessionDataTask
object).The completion handler is a closure and here's how you create that particular clousure:
{(data : NSData!, response : NSURLResponse!, error : NSError!) in // your code }
Here's the updated code:
let url = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
let request = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
// notice that I can omit the types of data, response and error
// your code
});
// do whatever you need with the task e.g. run
task.resume()
You can also use it simply by :-
let url = "api url"
let nsURL = NSURL
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
(data, response, error) in
// your condition on success and failure
}
task.resume()
If you have problems with completion syntax, you can create function for completion before calling dataTaskWithRequest(..) to make it clearer
func handler (data: NSData!, response: NSURLResponse!, error: NSError!) {
//handle what you need
}
session.dataTaskWithRequest(request, completionHandler: handler)