如何在Swift 3.0中将JSON数据显示到UILabel中?
我有三(3) UILabel名为登录,电子邮件和 pw
现在我设法在输出部分显示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()
}
}
感谢。
答案 0 :(得分:0)
您可以像这样解码您的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")
}