21

Can someone help me? I can't find a good example for the completion syntax.

var url : NSURL = NSURL.URLWithString("https://itunes.apple.com/search?term=\(searchTerm)&media=software")
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession.sessionWithConfiguration(config)

NSURLSessionDataTask(session.dataTaskWithRequest(request, completionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?)
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
DookieMan
  • 992
  • 3
  • 10
  • 26

6 Answers6

72

It's unclear what you're asking, but I noticed that you have a couple of errors in the code:

  1. You should create your session using NSURLSession(configuration: config)

  2. session.dataTaskWithRequest returns a NSURLSessionDataTask, so there's no need to wrap it inside NSURLSessionDataTask() (a.k.a instantiating a new NSURLSessionDataTask object).

  3. 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()
tobiasdm
  • 9,688
  • 1
  • 18
  • 15
akashivskyy
  • 44,342
  • 16
  • 106
  • 116
13

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)
Bogdan
  • 1,286
  • 9
  • 12
5

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()
Rachit
  • 814
  • 9
  • 19
2

Updated @duemonk's code for Swift 3:

do {
    var request = URLRequest(url: URL(string: "https://www.example.com/api/v1")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)

    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

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

         if error != nil {

              print(error!.localizedDescription)

         }

         else {
              print(response)
         }
     })

    task.resume()
}

catch {
// handle the error
}
1

Swift 4.2

    let url = URL(string: "http://url.com")!
    let request = URLRequest(url: url)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
        print(String(data: data!, encoding: .utf8)!)
    });

    task.resume()
Oktay
  • 423
  • 1
  • 6
  • 19
0
session.dataTaskWithRequest(request, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) in 
    //code
)}

Hopefully Xcode will be updated to support auto-complete for these, cause the syntax is kind of tricky, and Swift doesn't appear to support declaring the return type yet when used like this.

malhal
  • 26,330
  • 7
  • 115
  • 133
  • Yea, I've noticed that the auto-complete when using swift is pretty hit and miss. There have been a couple of instances that it stopped working all together and I had to restart Xcode. – DookieMan Jun 11 '14 at 21:37
  • I noticed that even in the Xcode 6.1 GM the auto-complete of params inside the closure doesn't work. And you cant "Jump to definition" while the syntax is incorrect, making the feature rather useless. – malhal Oct 05 '14 at 15:34