Swift 2中的HTTP请求和条件

时间:2016-07-05 12:39:23

标签: json swift http nsarray

我是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”错误。 服务器发送仅包含01的Json_encode数组(例如:["1","0","0","1","0"])。 我只是想得到这个回应,并为此做条件,但我做不到。 请帮忙,谢谢。

1 个答案:

答案 0 :(得分: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()
}