I've created a method which returns an array, but the array gets constructed inside of a completion handler of URLSession.shared.dataTask(with: URL) method. I inserted a url and the data task gets executed fine. I used the debug logger to check up on the array and it gets constructed perfectly (appending multiple objects to the array using a for-in loop). Only problem is after the completion handler (so after I called task.resume() method), the same array that got constructed inside the completion handler is suddenly empty and contains 0 elements. How can I get objects created inside of a completion handler to use them afterwards (for example if I want to return the object to the caller of the method in which the dataTask was started)?
            Asked
            
        
        
            Active
            
        
            Viewed 224 times
        
    0
            
            
        
        Sanoj Kashyap
        
- 5,020
 - 4
 - 49
 - 75
 
        Freddy Benson
        
- 735
 - 4
 - 11
 - 30
 
- 
                    2Please post your actual code. – Kurt Revis Sep 24 '16 at 18:19
 - 
                    You are running an asynchronous method and thus it can't wait for it to finish before returning the array otherwise it would be a synchronous method. – Leo Dabus Sep 24 '16 at 18:26
 - 
                    What you need is to pass the resulto using the completion handler, to post a notification or use a delegate – Leo Dabus Sep 24 '16 at 18:30
 - 
                    After calling resume just means the session started – Leo Dabus Sep 24 '16 at 18:32
 - 
                    http://stackoverflow.com/a/35358750/2303865 – Leo Dabus Sep 24 '16 at 18:51