0

I am writing a Network class for my app. One function carries out the actual request to the API I am using

as part of this function I am using a URLSession.shard.dataTask().

var decodedResponse = SongLinkAPIResponse()
        
let task = session.dataTask(with: url) { data, response, error in
            
            let result = data.map(Result.success) ?? Result.failure(DataLoaderError.network(error!))
            let handlerResult = handler(result)
//          This handler just decodes the downloaded JSON into a SongLinkAPIResponse struct. 
//          This works fine and I can see this is working
            


            DispatchQueue.main.async {
                switch handlerResult {
                    case .success(let response):
//                      When I run this code in a playground I can see that this line shows as working in the sidebar

                        decodedResponse = response
                    case .failure(let error):
                        print(error)
                }
            }
        }
        
task.resume()

//However when returning this variable it just has the empty default configuration of the struct

return decodedResponse

Any ideas on why the variable is not updating? Thanks in advance

Harry Day
  • 378
  • 4
  • 13
  • Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – pawello2222 Jul 04 '20 at 21:54

1 Answers1

1

session.dataTask is asynchronous. It will execute some time in the future.

Your code will execute in the following order.

// 1
var decodedResponse = SongLinkAPIResponse()

// 2        
let task = session.dataTask(with: url) { data, response, error in
            // 4
            ...
        }
        
task.resume()

// 3
return decodedResponse

Here are some possible explanations/solutions:

pawello2222
  • 46,897
  • 22
  • 145
  • 209