我是Swift的新手,找不到此代码的解决方案:
func presentationlum() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://raspberrypi.local/etatlum.php")!)
let Session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
var JsonDict=NSArray()
let dem = Session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do{
JsonDict = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0) )as! NSArray
}
print(JsonDict)
})
dem.resume()
if JsonDict[0] as! String == "0"
{
print("it works !")
}
else
{
print("it works to !")
}
}
构建它时,出现“线程1:信号SIGABRT”错误。
服务器发送仅包含
0
或1
的Json_encode数组(示例:["1","0","0","1","0"]
)。我只想得到此响应并对其进行处理,但我不能。
请帮忙,谢谢。
最佳答案
您需要在块完成之前访问答案:
func presentationlum() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://raspberrypi.local/etatlum.php")!)
let Session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
var JsonDict : NSArray
let dem = Session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
do{
if let _JsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions() )as? NSArray
{
JsonDict = _JsonDict
if JsonDict[0] as! String == "0"{
print("it works !")
}else{
print("it works to !")
}
}else{
print("Cannot parse JSON answer")
}
}catch {
print("An Error as occurred : \(error)")
}
print(JsonDict)
})
dem.resume()
}