【问题标题】:How to display JSON in a UILabel如何在 UILabel 中显示 JSON
【发布时间】:2017-03-30 20:47:41
【问题描述】:

我正在尝试将检索到的 JSON 数据显示为 UILabel。目前我已在调试器中成功显示数据,但我不确定如何将数据设置为等效于 UILabel。任何帮助,将不胜感激。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad()
{
    super.viewDidLoad()

    let url = URL(string: "http://cgi.soic.indiana.edu/~team10/index.php")

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil
        {
            print ("ERROR")
        }
        else
        {
            if let content = data
            {
                do
                {
                    //Array
                    let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        print(myJson)

                }
                catch
                {

                }
            }
        }
    }
    task.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

【问题讨论】:

    标签: json swift3 uilabel xcode8 ios10


    【解决方案1】:

    你可以试试下面的代码(dataURLSession dataTask中回调方法的参数):

    let body = try? JSONSerialization.jsonObject(with: data!, options: []) as AnyObject
    var jsonString = String()
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
        jsonString = String(data: jsonData, encoding: .utf8)!
        print("jsonString: \(jsonString)")
    } catch let error as NSError {
        print(error)
    }          
    DispatchQueue.main.async {
        self.sampleLabel.text = jsonString
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多