How to parse json data in UITableview using swift 3.0
import UIKit
class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
// var items: [String] = ["let's", "start", "Swift"]
var Namearray: [String] = []
var Email: [String] = []
override func viewDidLoad()
{
super.viewDidLoad()
table = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
table.delegate = self
table.dataSource = self
table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(table)
makeGetRequest()
}
func makeGetRequest(){
//create the url with NSURL
let url = URL(string: "http://api.androidhive.info/contacts/")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
let request = URLRequest(url: url)
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do{
let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:AnyObject]
if (json != nil) {
// Success
print(json)
let dataArray = json["contacts"] as! NSArray;
for item in dataArray
{
// loop through data items
let obj = item as! NSDictionary
let names = obj["name"] as! NSString
print(names)
let emails = obj["email"] as! NSString
print(emails)
self.Namearray.append(names as String)
self.Email.append(emails as String)
for (key, value) in obj {
print("Key: \(key) - Value: \(value)")
let phone = obj["phone"] as! NSDictionary;
let mobile = phone["mobile"] as! NSString
print(mobile)
let home = phone["home"] as! NSString
print(home)
let office = phone["office"] as! NSString
print(office)
}
}
}
//swift 3
DispatchQueue.main.async{
self.table.reloadData()
}
}
catch {
print("Error with Json: \(error)")
}
})
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Namearray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
cell.textLabel!.text = Namearray [indexPath.row] as NSString as String
cell.detailTextLabel!.text = Email [indexPath.row] as NSString as String
return cell;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
NSLog("You selected cell #\(indexPath.row)!")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Comments
Post a Comment