json - Swift 2 中的 HTTP 请求和条件

标签 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 “])。 我只想得到这个响应并用它做条件,但我不能。 请帮忙,谢谢。

最佳答案

您正在 block 完成之前访问您的答案:

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

关于json - Swift 2 中的 HTTP 请求和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203703/

相关文章:

json - 在 Golang 中解析 JSON 时出错

java - RestTemplate 映射到 Map 而不是字段

Swift 4 - 获得按钮宽度的一半

ios - 如何使用 swift 2 在后台应用程序时更新位置

json - RapidJson 和 Boost Json 解析器

javascript - 按输入日期过滤 ng-repeat

Swift:分配一个变量以指向一个数组(与复制相比)

json - XMLHttpRequest 无法加载,但响应显示 200 状态

jquery - 如何获取 iframe 响应 http 代码 onload?

python - http响应与站点和代码输出不同的原因是什么?