将JSON数据传递给Swift中的标签

时间:2015-10-29 04:59:14

标签: json swift

我是编码的新手,并且有一个(希望很容易)的问题。

我正在尝试使用swift将JSON数据显示为标签。我没有收到任何错误,但使用以下代码没有显示任何错误:

  let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, ErrorType) -> Void in

        if let urlContent = data {

            do {

            let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)

                print(jsonResult)

                let text = jsonResult as? String

                self.textLabel.text = text

            } catch {

                print("JSON serialization failed")

            }

        }

    }

    task.resume()

谢谢!

1 个答案:

答案 0 :(得分:3)

只需将您的标签更新为主线程:

dispatch_async(dispatch_get_main_queue()) {
    self.textLabel.text = text
}

<强>更新

您可以使用SwiftyJSON

以下是您使用该库的工作代码:

import UIKit

class ViewController: UIViewController {

    var dict = NSDictionary()

    @IBOutlet weak var authorLbl: UILabel!
    @IBOutlet weak var quoteLbl: UILabel!

    override func viewDidLoad() {

        super.viewDidLoad()

        let urlString = "http://api.theysaidso.com/qod.json"

        if let url = NSURL(string: urlString) {

            if let data = try? NSData(contentsOfURL: url, options: []) {

                let json = JSON(data: data)

                print(json)

                let auther = json["contents"]["quotes"][0]["author"].stringValue

                let quote = json["contents"]["quotes"][0]["quote"].stringValue

                authorLbl.text = auther

                quoteLbl.text = quote

            }

        }

    }
}