Web请求确实无法正常工作

时间:2016-11-14 20:34:53

标签: ios json swift web swift3

我想创建一个调用服务器并获取JSON信息的App。服务器返回的是:

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

我的代码是这样的:

    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()

我正在MainViewController的viewDidLoad函数中执行它。 我得到输出“每个人都很好,文件dl成功”但没有更多的输出。在do块中没有那个,也没有在catch中输出并且它没有改变UILabels。 但是在我的WebServer上我可以看到它发出了请求!

任何想法为什么? 我通过http连接并将App Transport Security Settings中的Allow Arbitrary Loads设置为yes(info.plist)

dunklesToast

1 个答案:

答案 0 :(得分:1)

作为浮动投射应该让你去。我建议添加一个else来处理一个转换失败。

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

 if let hum = json["humidity"] as? Float {
           self.hum.text = hum + "\(hum)°C";
           print(hum);
 }
 else{
 //handle this outcome
 }
相关问题