Forked from ashishkakkad8/JOSNArraySwiftParsingiOS
Created
November 17, 2017 19:04
-
-
Save ecr007/fbdd118fa69fb24853cd63360ad6aa61 to your computer and use it in GitHub Desktop.
JSON Array Parsing in Swift Langauage - Swift 3 – iOS 10 – Xcode 8 GM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// SwiftJSONParsingDemo | |
// | |
// Created by Ashish Kakkad on 12/10/16. | |
// Copyright © 2016 Kode. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var tableView: UITableView! | |
var names: [String] = [] | |
var contacts: [String] = [] | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let url=URL(string:"http://api.androidhive.info/contacts/") | |
do { | |
let allContactsData = try Data(contentsOf: url!) | |
let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] | |
if let arrJSON = allContacts["contacts"] { | |
for index in 0...arrJSON.count-1 { | |
let aObject = arrJSON[index] as! [String : AnyObject] | |
names.append(aObject["name"] as! String) | |
contacts.append(aObject["email"] as! String) | |
} | |
} | |
print(names) | |
print(contacts) | |
self.tableView.reloadData() | |
} | |
catch { | |
} | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { | |
return self.names.count; | |
} | |
func tableView(_ tableView: UITableView!, didSelectRowAtIndexPath indexPath: IndexPath!) { | |
print("You selected name : "+names[indexPath.row]) | |
} | |
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{ | |
var cell = tableView.dequeueReusableCell(withIdentifier: "cell") | |
if !(cell != nil) { | |
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") | |
} | |
cell?.textLabel?.text=self.names[indexPath.row] | |
cell?.detailTextLabel?.text = self.contacts[indexPath.row] | |
return cell! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment