19
var session = NSURLSession.sharedSession()
session.dataTaskWithRequest(urlRequest, 
                            completionHandler: {(data: NSData!, 
                                                 response: NSURLResponse!,                       
                                                 error: NSError!) in
                                                      println(data)
                                                      println(response)
                                                      println(error)
                                               })

So I am making this request, and the completion block is never called.

What's wrong?

Also I tried a synchronous and asynchronous form of the same request with NSURLConnection and it worked perfectly.

EDIT:

I tried assigning a dataTask variable to the session.dataTaskWithRequest and displayed it right after. It says this <__NSCFLocalDataTask: 0xb41bda0> { suspended } Suspended? Why?

Yoav
  • 5,962
  • 5
  • 39
  • 61
esh
  • 2,842
  • 5
  • 23
  • 39

6 Answers6

55

So I tried calling it like this

session.dataTaskWithRequest(urlRequest, 
                        completionHandler: {(data: NSData!, 
                                             response: NSURLResponse!,                       
                                             error: NSError!) in
                                                  print(data)
                                                  print(response)
                                                  print(error)
                                           }).resume()

And it worked.

Seems like I have to call resume() on a default suspended session task.

esh
  • 2,842
  • 5
  • 23
  • 39
  • 9
    Yes. This is the same in Swift or Objective C; all NSURLSession tasks start in a suspended state and must be "resumed" to kick them off. It's Objective C-based, but [this NSURLSession tutorial from raywenderlich.com](http://www.raywenderlich.com/51127/nsurlsession-tutorial) is the best non-Apple example of NSURLSession code I've come across, so having a look through that might help you work out how best to use it. – Matt Gibson Jun 05 '14 at 10:07
  • didn't help me at all :( – Serge Velikan Dec 03 '15 at 23:07
  • @SergeVelikanov what did you try? – esh Dec 08 '15 at 11:37
  • @BlackFlam3, nevermind, I'm using AFNetworking now and it works like a charm – Serge Velikan Dec 08 '15 at 12:35
7

Are you using playgrounds??

If you are, you should be careful to include:

 XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

In order to make the playground wait for the callback

supersabbath
  • 364
  • 3
  • 8
5

I face the same problem and I solved it by

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {

    if (!error)
    {
        NSLog(@"Data is %@",data);
        NSLog(@"Response is %@",response);
        NSLog(@"Error is %@",error);
    }
 }];

[dataTask resume];

And check that you are added the App Transport Security Settings in your info.plist.

Ramakrishna
  • 712
  • 8
  • 26
3

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
1

This is a fairly unique case, but if you're using a URLSession inside a unit test, you'll need to setup the expectations. Otherwise, your test case will end and it will appear that your request is never returning. Swift 3.0.1.

    let expect = expectation(description: "dataTaskWithRequest - completes")

    if let url = URL(string: "https://www.google.com/") {

        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { ( data, response, error) in

            print(data.debugDescription)
            print(response.debugDescription)
            print(error.debugDescription)

            expect.fulfill()

        }.resume()

        waitForExpectations(timeout: 10, handler: nil)
    }
Justin Domnitz
  • 3,217
  • 27
  • 34
0

It'll be something like this in Swift 2.x

NSURLSession.sharedSession().dataTaskWithRequest(theRequest) { (data, response , error) in
    print(response)
}.resume()
Jay Mayu
  • 17,023
  • 32
  • 114
  • 148