I have these JSON data.
(
{
email = "b@p.com.my";
login = ID001;
pw = 1234;
},
{
email = "p@d.com.my";
login = ID002;
pw = 12345;
}
)
Right now, I can only print myJSON value in x code output.
My question is, how to display each JSON into UILabel _email, _login, _pw?
Someone said that I need to store as variable and set into UILabel but i don't know how to do it. Appreciate if someone can help me on this matters.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBOutlet var _email: UILabel!
@IBOutlet var _login: 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")
return
}
else {
if let content = data {
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJSON)
}
catch {}
}
}
}
task.resume()
}
}
Thanks.
EDIT: After the block where you print your myJSON, try this:
for eachItem in myJSON {
if let emailParsed = eachItem["email"] as? String {
print(emailParsed)
_email.text = emailParsed
}
}
This loop runs between all the dictionaries and This solution could be helpful for you. Please go through it!
Hi Please try this one
for i..0 < myJson.count {
let object = myJson[i] as AnyObject
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
EDITED
for i..0 < myJson.count {
let object = myJson[i] as [String : AnyObject]
if let emailParsed = myJSON["email"] as? String {
_email.text = emailParsed
}
}
It's simple because your json object gives an array of dictionary so first you have to take first object from array and after that you can take the string passing the key
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")
return
}
else
{
if let content = data
{
do {
let myJSON = try JSONSerialization.jsonObject(with: content, options:JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
// print(myJSON)
for data in myJSON
{
let email = data.1["email"] as? String
_email.text = email
}
}
catch {}
}
}
}
task.resume()
}
}
For batter option you can use some predefined libraries like swiftyJSON. To get best result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.