1

I have the following code but unsure why its not running:

 NSURLSession *session = [NSURLSession sharedSession];
 NSURLSessionDataTask *dataTask = [session dataTaskWithURL:
 [NSURL        URLWithString:myURLString] completionHandler:^
 (NSData *data, NSURLResponse *response, NSError *error) 
 {NSDictionary *json =   
  [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

 [self performSegueWithIdentifier:@"login" sender:self];}];


 [dataTask resume];

The preformSegueWithIdentifier works outside but not inside the brackets. But I have done something similar using NSUrlConnection and that works fine. I'm new to NSURLSession any ideas why the performSegueWithIdentifier doesn't run within the call.

Any ideas?

tau
  • 288
  • 4
  • 19
  • Take a look at this question. http://stackoverflow.com/questions/5023566/objective-c-calling-self-methodname-from-inside-a-block – Michael Jun 18 '14 at 21:46

1 Answers1

2

If you create the NSURLSession object the way you are, it creates a new serial operation queue that is not the main queue. The completion handler of the dataTaskWithURL: method is run on the session's queue, so it's not working because you're trying to do a UI task on a background queue. To fix it, create your session like this,

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
rdelmar
  • 103,982
  • 12
  • 207
  • 218