我在stackoverflow&上非常新。非常非常新的Swift。 我需要从PHP获得结果,使用如下的Swift代码:
func GetEtatO2()
{
let url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!,
completionHandler:
{
(data, response, error) -> Void in
if error != nil
{
print("Error: \(error)")
return
}
else
{
print("data ==> \(data)")
print("response ==> \(response)")
print("error ==> \(error)")
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString ==> \(responseString!)")
self.EtatO2 = responseString!
}
}
)
task.resume()
}
我的PHP代码返回的字符串是" ON" ou" OFF"。
我可以将此字符串作为我的代码的else
部分,但是,行self.EtatO2 = responseString!
似乎什么都不做;我的意思是价值" ON" ou" OFF"未存储在var EtatO2
。
我确定我想念比我更大的东西......你能帮一些忙吗? 非常感谢提前。
答案 0 :(得分:1)
我终于找到了解决方案:插入
dispatch_async(dispatch_get_main_queue(), { () -> Void in ...
as follow
`@IBAction func GetEtatO2(sender: UIButton) {
let Url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
let task = NSURLSession.sharedSession().dataTaskWithURL(Url!, completionHandler: { (data, response, error) -> Void in
print( ">>>> Debut >>>>")
print("Error: \(error)")
if error != nil
{
return
}
else
{
print("data: \(data)")
print("Response: \(response)")
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString: \(responseString)")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.EtatO2Label.text = responseString
})
}
print( "<<<< Fin <<<<")
})
task.resume()
}
通过这种方式,按下GetEtatO2按钮,在标签中显示正确的状态。
答案 1 :(得分:0)
确保在调用完成处理程序之后才尝试使用self.Etat02
。一种方法是向GetEtat02()
添加完成处理程序。
func GetEtatO2(completion:(String) -> ())
{
let url = NSURL(string: "http://www.exxagon.com/php/GetEtatO2.php")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!,
completionHandler:
{
(data, response, error) -> Void in
if error != nil
{
completion("Error: \(error)")
}
else
{
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
completion(responseString!)
}
}
)
task.resume()
}
然后您可以致电GetEtat02()
并使用这样的回复:
GetEtatO2() { responseString in
// This won't run until the NSURLSession completes
print(responseString)
}
// responseString doesn't exist here, only in the closure above