Display images in UITableview - json

I'm trying to display images from api in the tableview but I get no images or anything. ImageTableViewCell has the outlet to the image only.
import UIKit
import Alamofire
import SwiftyJSON
import Haneke
class SlideViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
#IBOutlet weak var tableview : UITableView!
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
getJSON()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell
let url = URL(string: images[indexPath.row])
cell.images.hnk_setImage(from: url!)
return cell
}
func getJSON() {
let url = "http://localhost:8000/api/hello"
request(url , method: .get, encoding: JSONEncoding.default )
.responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
do{
if let albums = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String: Any],
let pics = albums["pic"] as? [Any] {
self.images = pics as! [String]
for kick in pics {
self.images.append(kick as! String)
}
}
}catch {
print("Error with Json: \(error)")
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
}
}
}
Any help will be appreciated. I tried many methods but this seems to be simple and easy to follow up

Check below code
var images = [String]()
func getJSON() {
let url = "http://localhost:8000/api/hello"
request(url , method: .get, encoding: JSONEncoding.default )
.responseJSON { response in
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
do{
let albums = try JSONSerialization.jsonObject(with: response.data!, options:.allowFragments) as! [[String: AnyObject]]
print(albums)
if let pics = album["pic"]
{
for album in pics
{
images.append(album)
}
}
}catch {
print("Error with Json: \(error)")
}
self.tableview.reloadData()
}
}
}

Your JSON response is Dictionary not Array and its contains pic array inside of it. So type result of jsonObject(with:options:) to [String:Any] instead of [[String: AnyObject]]
do{
if let albums = try JSONSerialization.jsonObject(with: response.data!, options: []) as? [String: Any],
let pics = albums["pics"] as? [Any] {
images = pics.flatMap{ $0 as? String }
}
}catch {
print("Error with Json: \(error)")
}
DispatchQueue.main.async {
self.tableview.reloadData()
}

You must have at least one section to show.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

Related

How to push different view controller from collection view didSelectItemAt based on Json id in swift

My project contains collectionView.. but how to push different viewcontroller from didSelectItemAt based on json id.. and i have separate vewcontrollers for each id.. but i am unable to push different viewcontrolls with didSelectItemAt based on json id.
here is my Json for collectionView:
{
"financer": [
{
"id": "45",
"icon": "https://hello.com//images/img1.png"
}
{
"id": "40",
"icon": "https://hello.com//images/img2.png"
}
.
.
.
]
}
here is my home collectionview code:
import UIKit
struct JsonData {
var iconHome: String?
init(icon: String, tpe: String) {
self.iconHome = icon
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var idArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
//Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
if let url = NSURL(string: aData.iconHome ?? "") {
if let data = NSData(contentsOf: url as URL) {
cell.paymentImage.image = UIImage(data: data as Data)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
let indexPathHome = indexPath.row
print("home collectionItem indexpath \(indexPathHome)")
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.com/webservices/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
print("home financer id \(id)")
self.idArray.append(id)
print("the home financer idsArray \(self.idArray.append(id))")
self.itemsArray.append(JsonData(icon: pic ?? ""))
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
}
when I click on any item from collectionview i am able to push same view controller but i need to push different view controller based on json id. i dont know how to and where to use json id to push differnt viewcontroller using didselectItem atIndexPath. anyone please help me here.
Update your homeServiceCall function
func homeServiceCall(){
let urlStr = "https://dev.com/webservices/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
let financerArray = jsonObj["financer"] as! [[String: Any]]
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
self.itemsArray.append(JsonData(icon: pic ?? ""))
self.idArray.append(id)
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
Create a string property called financerId in your MakePaymentViewController
In your didSelect function
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as? MakePaymentViewController {
nextViewController.finacerId = idArray[indexPath.row]
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
Update
for financer in financerArray {
if let id = financer["id"] as? Int {
self.idArray.append(id)
}
if let pic = financer["icon"] as? String {
elf.itemsArray.append(JsonData(icon: pic))
}
}

JSON parsing swift 3

if statusCode == 200 {
let json = response.result.value as? NSDictionary
print("JSON FILE")
//print(json)
let companies = json?["companies"] as? [AnyObject]
print(companies)
for value in companies! {
let address = value["address"] as? String
print(address)
let schedule = companies?["schedule"] as? [AnyObject]// as? NSDictionary
print(schedule)
for sch in schedule! {
}
}
}
Here json file
{
"code": "200",
"message": "OK",
"companies": [
{
"id": "1",
"img": "doxsun.jpg",
"schedule": [
{
"id": "1",
"company_id": "1",
"day": "0",
"time_from": "06:00:00",
"time_to": "23:00:00"
}
]
},
{
"id": "2",
"img": "zalypa.jpg",
"schedule": []
}
]
}
I have a problem with json file parsing how correctly parse it? I can't parse schedule. How to convert all this types? words to pass quality. words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.words to pass quality.
There are some conversion issues with correct types using as operator. I believe the below code should allow you to iterate through schedules of each company:
if let JSON = response.result.value as? [String: AnyObject] {
if let companies = JSON["companies"] as? [[String: AnyObject]] {
for company in companies {
if let schedules = company["schedule"] as? [[String: AnyObject]] {
for schedule in schedules {
// do something with the schedule
}
}
}
}
}
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return 2 //datamodel.count
return newarr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: tblCell.identifier, for: indexPath) as! tblCell
self.json = newarr.object(at: indexPath.row) as! NSDictionary
cell.lblName.text = json.value(forKey: "artistName") as? String
return cell
}
}
extension ViewController {
func swiftyJson(){
let url = URL(string: "https://itunes.apple.com/search?term=jack+johnson")
//let url = URL(string: "http://makani.bitstaging.in/api/business/businesses_list")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
let data = response.result.value as! NSDictionary
self.newarr = data.value(forKey: "results")as! NSArray
print(self.newarr)
self.tblView.reloadData()
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
}
let url = URL(string: "https://api.androidhive.info/contacts")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
if let dicData = response.result.value as? [String : Any]{
if let arrOfCartDetails = Mapper<BaseDataModel>().map(JSON: dicData) {
self.arrData.append(arrOfCartDetails)
print(self.arrData)
if self.arrData.count > 0{
self.arrContect = self.arrData[0].contacts!
print(self.arrContect[0].phone?.home)
}
if self.arrContect.count > 0{
self.tblDemo.reloadData()
}
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
let url = URL(string: "https://jsonplaceholder.typicode.com/todos")
Alamofire.request(url!, method: .get, parameters: nil).responseJSON { response in
switch(response.result) {
case .success(_):
if let data = response.result.value as? [[String : Any]]{
if Mapper<DocumentDataModel>().mapArray(JSONArray: data).count > 0{
self.arrDataModel = Mapper<DocumentDataModel>().mapArray(JSONArray: data)
print(self.arrDataModel)
let banner = self.arrDataModel[0]
print("userId", banner.userId)
if self.arrDataModel.count > 0{
self.tblDemo.reloadData()
}
}
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
let url = "https://reqres.in/api/products"
AF.request(url, method: .get, parameters: nil).responseJSON{ (response) in
switch(response.result) {
case .success(let responseString):
print("Success")
// print(responseString)
let User = Mapper<Response>().map(JSONObject:responseString)
// print(User)
self.arrayFavouriteJobList = (User?.data)!
print(self.arrayFavouriteJobList)
self.tblData.reloadData()
break
case .failure(_):
print(response.error as Any)
break
}
}
func apiCalling(){
let url = "https://jsonplaceholder.typicode.com/posts"
AF.request(url, method: .get, parameters: nil, headers: nil).responseJSON { (response) in
if let responseData = response.data{
print(response)
do{
let decodeJson = JSONDecoder()
decodeJson.keyDecodingStrategy = .convertFromSnakeCase
self.responseData = try decodeJson.decode([DataModel].self, from: responseData)
self.tblData.reloadData()
}catch{
}
}
}
}
Alamofire.request(url, method: .get, headers: nil).responseJSON{response in
switch response.result{
case.success:
print("sucess")
if let JSON = response.result.value
{
self.hk = JSON as! NSDictionary
print(self.hk)
print(((self.hk.value(forKey: "contacts")as! NSArray).object(at: 4 )as! NSDictionary).value(forKey: "name")as! NSString)
self.flag = 1
self.tbl1.reloadData()
}
case.failure(let Error):
print("error\(Error)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if flag == 0
{
return 0
}
else
{
return (self.hk.value(forKey: "contacts")as! NSArray).count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tbl1.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! TableViewCell1
cell.lbl1.text = (((self.hk.value(forKey: "contacts")as! NSArray).object(at: indexPath.row)as! NSDictionary).value(forKey: "name")as!String)
return cell
}
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource{
var hk : NSDictionary = NSDictionary()
let url = "https://itunes.apple.com/search?term=jack+johnson"
#IBOutlet var tblview: UITableView!
var flag = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
getdata()
}
func getdata()
{
//let url = "https://itunes.apple.com/search?term=jack+johnson"
Alamofire.request(url, method: .get, headers: nil).responseJSON{response in
switch response.result{
case.success:
print("sucess")
if let JSON = response.result.value
{
self.hk = JSON as! NSDictionary
print(self.hk)
print(((self.hk.value(forKey: "results")as! NSArray).object(at: 0)as! NSDictionary).value(forKey: "artworkUrl60")as! NSString)
//print(((self.hk.value(forKey: "contacts")as! NSArray).object(at: 4 )as! NSDictionary).value(forKey: "name")as! NSString)
self.flag = 1
self.tblview.reloadData()
}
case.failure(let Error):
print("error\(Error)")
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if flag == 0
{
return 0
}
else
{
return (self.hk.value(forKey: "results")as! NSArray).count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as! TableViewCell1
let imageURL = NSURL(string: (((self.hk.value(forKey: "results")as! NSArray).object(at: indexPath.row) as! NSDictionary).value(forKey: "artworkUrl60") as! String))
let imagedData = NSData(contentsOf: imageURL! as URL)!
cell.img1.image = UIImage(data: imagedData as Data)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let bh = storyboard?.instantiateViewController(withIdentifier: "imageViewController")as!imageViewController
bh.str = (((self.hk.value(forKey: "results")as! NSArray).object(at: indexPath.row) as! NSDictionary).value(forKey: "artworkUrl60") as! String)
self.navigationController?.pushViewController(bh, animated: true)
}
// swifty Json
func jsonParsing(){
let url = URL(string: "https://api.androidhive.info/contacts/")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do{
let json = JSON(data:data)
let contacts = json["contacts"][5]["phone"].dictionaryValue
print(contacts)
}
catch{
print(error.localizedDescription)
}
}.resume()
}
func jsonParsing(){
let url = URL(string: "https://api.androidhive.info/contacts/")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
guard let data = data else { return }
do{
let json = JSON(data:data)
let contacts = json["contacts"]
let name = contacts["name"]
for arr in contacts.arrayValue{
print(arr["name"])
}
//prinerrrr)
}
catch{
print(error.localizedDescription)
}
}.resume()
}
}

How to parse this json with Alamofire 4 in Swift 3?

I have the json below but unable to figure out how to parse it in Swift 3. My code is below. The json from the API has an array root. I am using Xcode 8.2.1 with Swift 4 and Alamofire 4.0.
["items": <__NSArrayM 0x608000248af0>(
{
currency = USD;
image = "https://cdn.myDomain.com/image.jpg";
"item_title" = "Antique Table";
"name:" = "";
price = 675;
},
{
currency = USD;
image = "https://cdn.mydomain.com/image2.jpg";
"name:" = "";
price = 950;
...
Here is my code. I have tried to get an array r dictionary from the results but it's always nil.
Alamofire.request(myURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.mutableContainers) as! [String: Any]
print(readableJSON)
}
catch {
print(error)
}
}
I have tried this let item = readableJSON["items"] as? [[String: Any]] as suggested here but it would not compile with an error [String:Any] has no subscript and let item = readableJSON["items"] as? [String: Any]! compiles with a warning Expression implicitly coerced from string but produces nil. Parsing this json is life or death for me.
Do something like
let responseJSON = response.result.value as! [String:AnyObject]
then you'll be able to access elements in that dictionary like so:
let infoElementString = responseJSON["infoElement"] as! String
This was the parse json function I eventually came up with. The problem for this json data is that it is a dictionary inside an array. I am a noob and most of the answers and how tos I saw would not fit my json data. Here is the function I finally came up with with worked.
var myItems = [[String:Any]]()
then in my view controller class
func loadMyItems() {
Alamofire.request(myItemsURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
self.collectionView.reloadData()
})
}
func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.allowFragments) as! [String: Any]
let items = readableJSON["items"] as! [[String: Any]]
self.myItems = items
}
catch {
print(error)
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? myCell
let dictionary = myItems[indexPath.row] as [String:Any]
if let item_title = dictionary["item_title"] as? String {
cell!.textLabel.text = item_title
print(item_title)
}
return cell!
}
Alamofire Example in Swift 3
1.First of all Use two cocoapods to your project.Use SwiftyJSON for json parse
pod 'Alamofire'
pod 'SwiftyJSON'
My Json is below
{"loginNodes":[{"errorMessage":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
It may be done in different way. But I have done below Way. Note if you don't need any parameter to send the server then remove parameter option. It may work post or get method. You can use any way. My Alamofire code is below...which is working fine for me......
Alamofire.request("http://era.com.bd/UserSignInSV", method: .post,parameters:["uname":txtUserId.text!,"pass":txtPassword.text!]).responseJSON{(responseData) -> Void in
if((responseData.result.value != nil)){
let jsonData = JSON(responseData.result.value)
if let arrJSON = jsonData["loginNodes"].arrayObject {
for index in 0...arrJSON.count-1 {
let aObject = arrJSON[index] as! [String : AnyObject]
let errorCode = aObject["errorCode"] as? String;
let errorMessage = aObject["errorMessage"] as? String;
if("0"==errorCode ){
//Database Login Success Action
}else{
// //Database Login Fail Action
}
}
}
}
}
If You use Like table View Or Collection View or so on, you can use like that..
Declare A Array
var arrRes = [String:AnyObject]
Assign the value to array like
if((responseData.result.value != nil)){
// let jsonData = JSON(responseData.result.value)
if((responseData.result.value != nil)){
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["loginNodes"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.tableView.reloadData()
}
}
}
In taleView, cellForRowAt indexPath , Just use
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! customCell
cell.errorLabelName.text = arrRes[indexPath.row]["errorMessage"] as? String
Swift 3
Alamofire Example in Swift 3
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
var array = [[String:AnyObject]]()
#IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Alamofire.request("http://www.designer321.com/johnsagar/plumbingapp/webservice/list_advertise.php?zip=123456").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil)
{
let swiftyJsonVar = JSON(responseData.result.value!)
print("Main Responce")
print(swiftyJsonVar)
}
if let result = responseData.result.value
{
if let Res = (result as AnyObject).value(forKey: "response") as? NSDictionary
{
if let Hallo = (Res as AnyObject).value(forKey: "advertise_list") as? NSArray
{
print("-=-=-=-=-=-=-")
print(Hallo)
self.array = Hallo as! [[String:AnyObject]]
print(self.array)
}
}
self.tableview.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
var dict = array[indexPath.row]
cell.lbl1.text = dict["address"] as? String
cell.lbl2.text = dict["ad_created_date"] as? String
cell.lbl3.text = dict["phone_number"] as? String
cell.lbl4.text = dict["id"] as? String
cell.lbl5.text = dict["ad_zip"] as? String
let imageUrlString = dict["ad_path"]
let imageUrl:URL = URL(string: imageUrlString as! String)!
let imageData:NSData = NSData(contentsOf: imageUrl)!
cell.img.image = UIImage(data: imageData as Data)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100
}
}

Hi there , I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data

I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data.
''import UIKit
class
FirstViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{
#IBOutlet weak var tableview: UITableView!
var TableData:Array< String > = Array < String >()
var valueToPass:String!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstViewCell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let countries_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let country_name = country_obj["country"] as? String
{
if let country_code = country_obj["code"] as? String
{
TableData.append(country_name + " [" + country_code + "]")
}
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
tableview.reloadData()
}
}
you need to set tableView's dataSource and delegate to self.

append is not working

I have parsed a json string and i want to use it in a tableview. when i try to append the json string into an array the append method is not working. Here is the code that i have used. Can anyone help me with this?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var userName = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// 1
let urlAsString = "http://demo.codeofaninja.com/tutorials/json-example-with-php/index.php"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
// 3
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
/*let err: NSError!
if (err != nil) {
print("JSON Error \(err.localizedDescription)")
}*/
// 4
//let fname: String! = jsonResult["firstname"] as! String
//let lname: String! = jsonResult["lastname"] as! String
//let usrname: String! = jsonResult["username"] as! String
dispatch_async(dispatch_get_main_queue(), {
if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]]
{
for user in users
{
print("First Name:")
print(user["firstname"]!)
print("Last Name:")
print(user["lastname"]!)
print("User Name:")
let nameUser = user["username"]! as! String
print(nameUser)
self.userName.append(nameUser)
print("***************")
}
}
//print(jsonResult["Users"]!)
//print(lname)
//print(usrname)
})
}
catch {
print("error");
}
})
jsonQuery.resume()
//self.userName.append("ganesh")
// 5
print(userName)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
cell.textLabel?.text = userName[indexPath.row]
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
userName.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You are appending right in the array,Just call self.tableView.reloadData() to refresh table view at the end of dispatch to show the data in the tableView.
The append function works fine but you are filling the array in the background and never reloading the tableView when you have the data in the array
for user in users
{
if let nameUser = user["username"] as? String {
self.userName.append(nameUser)
}
}
self.tableView.reloadData()
Try this inside the if let users = jsonResult.objectForKey("Users") as? [[String:AnyObject]] block