completion handler doesn't called

Hello, i'am having a problem which i can't solve....I am trying to get a json code by an API request with URLSessionDataTask with a completion handler. However, my code inside my completion handler is never executed. When i am in debugger mode and execute my App line by line, i can see that all the code inside the completion handler is skipped. Here is my code :


import Foundation

class Market

{

var market: [String] = []

func getMarket()

{

let config = URLSessionConfiguration.default /

let session = URLSession(configuration: config) /

let url = URL(string: "https:/

let task = session.dataTask(with: url, completionHandler: {

(data, response, error) in

if error != nil {

print(error!.localizedDescription)

} else {

do {

print("debut du script json")

let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)

if let jsondata = json as? NSDictionary,

let results = jsondata["result"] as? NSArray

{

var marketCurrency : NSDictionary!

var currency : String!

var baseCurrency : String!

for i in 0...results.count-1

{

marketCurrency = results[i] as? NSDictionary

currency = marketCurrency["MarketCurrency"] as? String

baseCurrency = marketCurrency["BaseCurrency"] as? String

let coin : String = currency + "-" + baseCurrency

self.market.append(coin)

}

}

} catch {

print("error in JSONSerialization")

}

}

})

task.resume()

}

func returnMarket() -> [String]

{

return self.market

}

}

For next time, when you post code, format it to make reading easier :

-select the whole code

- click the formating tool : it is the <> sign at the top of the message.


    func getMarket()
    {
        let config = URLSessionConfiguration.default /
        let session = URLSession(configuration: config) /
        let url = URL(string: "https:/
        print("Entrée dans getmarket avec url ", url)          // To be added
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
        
            if error != nil {
            
                print(error!.localizedDescription)
            
            } else {
            
                do {
                    print("debut du script json")


Is getMarket called ?

You should insert a print at line 6 to check ; print the url as well, to make sure it's OK

do you go to line 10 ?

do you go to line 17 ?


Thanks to report exactly what you get on the log.

Thanks for your answer 🙂 Yes getMarket() is well called but in a other view. The url is ok when it printed at line 7.

I don't go to line 12 neither 19, i go directly to line 43.


Here's my log :


In fonction
https:/ 
(lldb)




func getMarket()
    {
      
        let config = URLSessionConfiguration.default /
        let session = URLSession(configuration: config) /
        let url = URL(string: "https:/
        print(url)
      
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
          
            if error != nil {
              
                print(error!.localizedDescription)
              
            } else {
              
                do {
                    print("debut du script json")
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                  
                    if let jsondata = json as? NSDictionary,
                        let results = jsondata["result"] as? NSArray
                    {
                        var marketCurrency : NSDictionary!
                        var currency : String!
                        var baseCurrency : String!
                      
                        for i in 0...results.count-1
                        {
                            marketCurrency = results[i] as? NSDictionary
                            currency = marketCurrency["MarketCurrency"] as? String
                            baseCurrency = marketCurrency["BaseCurrency"] as? String
                          
                            let coin : String = currency + "-" + baseCurrency
                            self.market.append(coin)
                        }
                    }
                } catch {
                    print("error in JSONSerialization")
                }
            }
        })
      
        task.resume()
    }

Ps: I tried with Alamofire and SwhityJSON and again my completionhandler isn't called. "In Fonction" was printed in the consol bu then I go directly to the line 23.



let url: String = "https:/
   
    func getBalance()
    {
        print("In fonction")
        Alamofire.request("https:/
           
            if((response.result.value) != nil)
            {
                let swiftyJsonVar = JSON(response.result.value!)
               
                if let resData =  swiftyJsonVar["Result"].arrayObject
                {
                    if let currency = resData[0] as? [String : AnyObject]
                    {
                        print(currency["Currency"])
                    }
                }
            }
           
           
           
}
}

Are you still trying in debugger mode and execute my App line by line ? If so, it is quite natural that all the code inside the completion handler is skipped.


The debugger cannot get into the completion handler with step by step execution. The completion handler is executed later when the communication is completed. So, for the debugger, the next step does not exist in the completion handler.


Remove the breakpoint, and see what you get in the debug console.

Many thanks man 🙂 I was always in debugger mode to see if my code running well. Now it's work perfectly !

completion handler doesn't called
 
 
Q