【问题标题】:Swift, Json Dictionary<String, AnyObject> send value to labelSwift,Json Dictionary<String, AnyObject> 将值发送到标签
【发布时间】:2017-04-21 06:06:39
【问题描述】:

我有一个 json,它返回给我一个字典。我可以在里面有值,但我想使用其中一个值来放入标签。我没有错误,但我视图中的标签没有改变。 这里代码:

let url = "http://localhost:8888/connexion/"+login!+"/"+password!
        let urlString = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
        let request = NSURLRequest(URL: NSURL(string: urlString)!)
        let alreadyTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
            guard let data = data, let _ = response  where error == nil else {
                print("error")
                return
            }
            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! Dictionary<String, AnyObject>
                print(json)
                print(json["3"] as! String)
                print(json["4"] as! String)
                print(json["5"] as! String)
                self.race_label.text = json["3"] as! String
                pa_label.text = json["5"] as! String
                name_label.text = json["4"] as! String
            } catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }

        })

        alreadyTask.resume()

    }

这里是日志:

["2": blabla12, "1": c@gmail.com, "3": orc, "4": test, "success": 1, "0": 5, "5": 100]

兽人 测试 100

所以,我不知道为什么它不起作用。谢谢!

【问题讨论】:

  • 你有日志吗?
  • 是的,对不起,我忘了^^现在有什么返回我的输出

标签: ios swift dictionary swift2 label


【解决方案1】:

您必须在主队列上执行与 UI 相关的工作。 dataTaskWithRequests 在后台队列中调用它的完成处理程序。

为了确保您的呼叫是在主队列上进行的,请替换:

self.race_label.text = json["3"] as! String
pa_label.text = json["5"] as! String
name_label.text = json["4"] as! String

与:

斯威夫特 2:

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.race_label.text = json["3"] as! String
    self.pa_label.text = json["5"] as! String
    self.name_label.text = json["4"] as! String
})

Swift3:

DispatchQueue.main.async {
    self.race_label.text = json["3"] as! String
    self.pa_label.text = json["5"] as! String
    self.name_label.text = json["4"] as! String
}    

【讨论】:

  • Xcode不知道dispatchQueue,也不明白是什么。这种观点不是我第一次呼吁。我有第一个带有连接的viewcontroller,在这里我想在ma DBB中有伪或种族或PA。
  • 你在使用 Swift3 吗?
  • 我使用的是 swift 2.1
  • 更新答案。
  • 你是完美的!非常感谢!!
猜你喜欢
  • 2016-08-16
  • 1970-01-01
  • 2015-12-13
  • 2016-09-29
  • 2016-05-28
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多