dunklesToast dunklesToast - 25 days ago 12
Swift Question

Web Request do catch not working

I want to create a little App which calls a Server and gets JSON Information. The thing the server returns is this:

{"temperature":23.60,"humidity":18.40}


My code is like this:

let requestURL: NSURL = NSURL(string: "http://esp_0b48a1:1337/")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in

let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
do{
let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

if let temp = json["temperature"] as? String {
self.degrees.text = temp + "°C";
print(temp);
}
if let hum = json["humidity"] as? String {
self.hum.text = hum + "%";
print(hum);
}
}catch{
print("error");
self.degrees.text = "no Temperature";
self.fill.text = "with";
self.degrees.text = "some errors like " + String(statusCode);
}
}
}

task.resume()


And I am executing it in the viewDidLoad function of my MainViewController.
I get the output "Everyone ist fine, file dl successfully" but no more output. Not that one in the the do block nor that output in the catch and its not changing the UILabels.
But on my WebServer I can see that it gots a request!

Any ideas why?
I am connecting via http and set the Allow Arbitrary Loads in App Transport Security Settings to yes (info.plist)

dunklesToast

Answer

Casting as a float should get you going. I'd suggest adding an else to handle a casting failure.

 if let temp = json["temperature"] as? Float {
                self.degrees.text = temp + "°C";
                print(temp);
 }else{
 //handle this outcome
 }

 if let hum = json["humidity"] as? Float {
           self.hum.text = hum + "%";
           print(hum);
 }
 else{
 //handle this outcome
 }