从HTTP请求获取值并刷新UIView标签值

时间:2019-06-05 09:09:46

标签: swift iphone xcode

我正在快速构建此函数,该函数执行HTTP请求以获取温度值,而不是使用此值,它应该在iPhone应用程序上显示它。

这是函数:

func getTemperatura()
{
    NSLog("getTemperatura")
    // qui devo fare una chiamata ed aggiornare la temperatura
    var myURLString = "http://" + url!.link!+"/TEMP";
    var temperatura = sendHttpRequestTemp(endPoint: myURLString)
    self.labelTemp.text = String(format: "%.0f", temperatura);
    self.labelDecimal.text = ".09";
    self.humText.text = "30%";
    temp = temp + 1;
}

这是方法sendHttpRequestTemp,它返回Double值。

func sendHttpRequestTemp(endPoint : String) -> Double{
    let url = URL(string: endPoint)!
    var valTemp = 0.0
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data,
        let response = response as? HTTPURLResponse,
        error == nil else {                                              // check for fundamental networking error
            print("error", error ?? "Unknown error")
            return
        }

        guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
            print("statusCode should be 2xx, but is \(response.statusCode)")
            print("response = \(response)")
            return
        }
        let responseString = String(data: data, encoding: .utf8)
        //RECUPERO I DATI RELATIVI ALLA TEMPERATURA:
        var temperatura = responseString!.components(separatedBy: "$");
        if(temperatura.count  > 1){
            print ("temperatura ricavata:  \(temperatura[1])");
            valTemp = Double(temperatura[1])!
        }
     //   print("responseString = \(responseString)")
    }

    task.resume()
    return valTemp
}

由于sendHttpRequestTemp方法为Async,然后返回temperature = 0.0而不是正确的值,因此无法正常工作。

此代码每60秒调用一次getTemperatura()方法:

var tempTimer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: Selector("getTemperatura"), userInfo: nil, repeats: true)

有一种方法可以正确执行此操作?

1 个答案:

答案 0 :(得分:2)

func sendHttpRequestTemp(endPoint : String, success: @escaping (Double) -> ()){
        let url = URL(string: endPoint)!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "GET"

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data,
            let response = response as? HTTPURLResponse,
            error == nil else {                                              // check for fundamental networking error
                print("error", error ?? "Unknown error")
                success(0.0)
                return
            }

            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }
            let responseString = String(data: data, encoding: .utf8)
            //RECUPERO I DATI RELATIVI ALLA TEMPERATURA:
            var temperatura = responseString!.components(separatedBy: "$");
            if(temperatura.count  > 1) {
                print ("temperatura ricavata:  \(temperatura[1])");
                let temp = Double(temperatura[1])!
                success(temp)
            }
            //   print("responseString = \(responseString)")
        }
        task.resume()
    }

注意:如果需要,请处理错误情况,如果发生错误,我将返回0.0。之后,您可以像这样调用函数:

func getTemperature() {
    NSLog("getTemperatura")
    // qui devo fare una chiamata ed aggiornare la temperatura
    var myURLString = "http://" + url!.link!+"/TEMP";
    sendHttpRequestTemp(endPoint: myURLString) { temp in
         self.labelTemp.text = String(format: "%.0f", temp);
    }
    self.labelDecimal.text = ".09";
    self.humText.text = "30%";
    temp = temp + 1;
}