0

I'm trying to test this piece of code to make sure I'm parsing the JSON correctly but the issue I'm running into is that nothing inside of the URLSession code block is getting executed. When I run the program, all I get is the "test2" print statement on the outside. If anyone could help point me in the right direction that would be greatly appreciated, thank you!

import Foundation

struct BMIInfo: Codable {
   let bmi: Double
   let more: [String]
   let risk: String
}

let url = "http://webstrar99.fulton.asu.edu/page3/Service1.svc/calculateBMI?height=60&weight=156"
let urlObj = URL(string: url)
URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in

   let dataAsString = String(data: data!, encoding: .utf8)
   let decoder = JSONDecoder()
   let jsonresult = try! decoder.decode(BMIInfo.self, from: data!)

   let bmi = jsonresult.bmi
   let more = jsonresult.more
   let risk = jsonresult.risk

   print(bmi)
   print(dataAsString)
   print("test")

}.resume()
print("test2")
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Stefan S.
  • 11
  • 1
  • Is it a console app? It's probable that your application will exit before the request is even done. – Sulthan Jun 29 '19 at 22:01
  • The code is supposed to work. In a Playground you might have to add the lines `import PlaygroundSupport` and `PlaygroundPage.current.needsIndefiniteExecution = true`. And be aware that the print order is **always** first `"test2"` then `"test"` – vadian Jun 30 '19 at 09:39
  • Hi Stefan, I didn't see anything wrong in your code. Hence I copied your code as-is in a new playground. And it just worked. I get following output: `test2 30.463333333333335 Optional("{\"bmi\":30.463333333333335,\"more\":[\"https:\\/\\/www.cdc.gov\\/healthyweight\\/assessing\\/bmi\\/index.html\",\"https:\\/\\/www.nhlbi.nih.gov\\/health\\/educational\\/lose_wt\\/index.htm\",\"https:\\/\\/www.ucsfhealth.org\\/education\\/body_mass_index_tool\\/\"],\"risk\":\"You are obese :(\"}") test` I am using Xcode 10.2.1. What are you using? – Pankaj Kulkarni Jul 01 '19 at 07:49

1 Answers1

0

Do you have any other errors? I took your code and put it in a playground and all of the print statements worked. I got 30.463333333333335 for the bmi, and I even added a print statement for risk and got that successfully. The "test2" does print first before any of the others. Do you have anything else going on which could be causing the URLSession to not be able to complete?

Ryan
  • 56
  • 1
  • 10