0

I have a question about NSURLSession I have downloaded JSON data using NSURLSession I want to access the JSON enter code hereData variable from outside this block of code so I manipulate it

this is my code

 // variable declared in my class
 var jsonData = JSON("")

// my function
 func loadCategories(){

var url = NSURL(string: "http://localhost:8888/api/v1/getAllCategories")

var request = NSMutableURLRequest(URL:url!)

request.HTTPMethod = "GET"

NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, errors: NSError!) in

self.jsonData = JSON(data: data)
 }).resume()
 }

When I try to get jsonData outside the block of NSURLSession I get empty variable

Any help ?

Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42
rayzer
  • 9
  • 1
  • Print the jsonData inside of the block. Is it not empty then? – dasdom Aug 11 '15 at 11:06
  • inside the block it's not empty, but later in an other method when I print it I get empty variable – rayzer Aug 11 '15 at 11:11
  • Check if the above code is called before the code where you read it. And make sure that the property isn't set somewhere else. Check if you are accessing the jsonData on the same thread. Maybe you have a race condition here. – dasdom Aug 11 '15 at 11:14
  • @dasdom I have found the solution let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.jsonData = JSON(data: data) dispatch_async(dispatch_get_main_queue()) { self.collectionView?reloadData() } } – rayzer Aug 11 '15 at 11:57
  • Yes, this is what I meant about same thread. :) I put it as an answer that you can check it as the correct answer. – dasdom Aug 11 '15 at 12:07

3 Answers3

0

Check if you are accessing the jsonData on the same thread. Maybe you have a race condition here.

dasdom
  • 13,975
  • 2
  • 47
  • 58
0

The problem is that you don't understand how async functions with completion blocks work.

Take a look at my answer to this thread. I explain what's going on in detail:

Why does Microsoft Azure (or Swift in general) fail to update a variable to return after a table query?

(Don't let the title of the thread mislead you. It has nothing to do with Microsoft Azure.)

The method you are using, dataTaskWithRequest, invokes your completion closure on the URL session's delegate queue. Unless you've provided a background queue as the delegate queue you don't need to bother with dispatch_async.

Community
  • 1
  • 1
Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

I have found the solution let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { self.jsonData = JSON(data: data) dispatch_async(dispatch_get_main_queue()) { self.collectionView?reloadData() } }

rayzer
  • 9
  • 1