gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:13:38 25 4
gpt4 key购买 nike

我是编码新手,有一个(希望很简单的)问题。

我正在尝试使用 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()

谢谢!

最佳答案

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

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

}

}

}
}

关于json - 将 JSON 数据传递给 Swift 中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com