【问题标题】:Display JSON data into UILabel in swift 3.0 ?在 swift 3.0 中将 JSON 数据显示到 UILabel 中?
【发布时间】:2017-01-11 08:47:49
【问题描述】:

如何在 Swift 3.0 中将 JSON 数据显示到 UILabel 中?

我有这 三 (3) 个 UILabel,分别名为 login,emailpw

现在我设法在输出部分显示 JSON,但我不知道如何将 JSON 数据显示到 UILabel 中。

这是我的 JSON 数据

[
    {"login":"ID001","pw":"123","email":"first@p.com"},
    {"login":"ID002","pw":"456","email":"second@p.com"}
]

还有我的 viewController.swift

import UIKit
class ViewController: UIViewController {
    @IBOutlet var login: UILabel!
    @IBOutlet var email: UILabel!
    @IBOutlet var pw: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "http://localhost/get.php")
        let task = URLSession.shared.dataTask(with: url!) {
            (data, response, error) in
            if error != nil {
                print("Error")
            }
            else {
                if let content = data {
                    do { 
                        let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        print(myJSON)
                    }
                    catch {

                    }
                }
            }
        }
        task.resume()
    }
}

谢谢。

【问题讨论】:

  • 您的 print(myjson) 是附加另一个数组,这些数组传入 label 它的简单 .

标签: json swift3 uilabel xcode8


【解决方案1】:

你可以像这样解码你的 json 数据。

do {
            if let myJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String:Any]] {
                print(json)
                for jsonDictionary in myJSON {
                    print(jsonDictionary["login"]!)
                    print(jsonDictionary["pw"]!)
                    print(jsonDictionary["email"]!)
                }
            }
        } catch {
            print("Something went wrong")
        }

【讨论】:

  • 感谢您的回复。但是如何让 UILabel 显示那些 JSON 数据。你能更新你的答案吗?谢谢。
  • 你的意思是,如何以编程方式创建 UILabel 或以编程方式设置数据 UILabel 文本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多