IOS 9 TableViewCell Not Visible Until Selected - uitableview

I use a service in a background thread to fetch a post request. Then I use NSJSONSerialization to turn that into an array. I loop thorough the array to create an array of teams. Then i go back to the main queue and call the completion handler.
Team:
class Team
{
private (set) var id: Int
private (set) var city: String
private (set) var name: String
private (set) var abbreviation: String
init(data: JSONDictionary)
{
id = data["team_id"] as? Int ?? 0
city = data["city"] as? String ?? ""
name = data["team_name"] as? String ?? ""
abbreviation = data["abbreviation"] as? String ?? ""
}
}
Service:
func getTeams(urlString: String, completion: [Team] -> Void)
{
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: config)
let url = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else {
print(data)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? JSONArray {
var teams = [Team]()
for team in json {
let team = Team(data: team as! JSONDictionary)
teams.append(team)
}
let priority = DISPATCH_QUEUE_PRIORITY_HIGH
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}
}
}
} catch {
print("error in NSJSONSerialization")
}
}
}
task.resume()
}
I then try to use data to populate a tableView. I also loop through and print out all the team names to the console with success. The problem I am having It populate the tableView but everything is all white. I cant see any txt from my labels until I touch it. While the table cell is selected I can see the contents of the labels which are in black. But if i touch another one only the currently selected label is showing. It seems they should all just show up visible once the data is loaded.
custom cell:
class TeamTableViewCell: UITableViewCell {
var team: Team? {
didSet {
updateCell()
}
}
#IBOutlet weak var title: UILabel!
#IBOutlet weak var abbreviation: UILabel!
func updateCell()
{
title.text = team?.name ?? ""
abbreviation.text = team?.abbreviation ?? ""
}
}
Controller:
var teams = [Team]()
override func viewDidLoad() {
super.viewDidLoad()
title = "Teams"
let service = NBAService()
service.getTeams("https://probasketballapi.com/teams?api_key=\(Constants.API.APIKey)", completion: didLoadTeams )
}
func didLoadTeams(teams: [Team])
{
self.teams = teams
tableView.reloadData()
// This actuall works returns an list of team names to the console.
for team in teams {
print("Team: \(team.name)")
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return teams.count
}
struct Storyboard {
static let TeamCell = "TeamCell"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TeamCell, forIndexPath: indexPath) as! TeamTableViewCell
// Configure the cell...
cell.team = self.teams[indexPath.row]
return cell
}
When i print the teams names to the console that prints fine so I know that I have successfully got the data back from the request. And one team at a time is visible when the cell is selected. What am I missing

This is kind of strange:
dispatch_async(dispatch_get_global_queue(priority, 0)) {
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}
}
I would replace this with:
dispatch_async(dispatch_get_main_queue()) {
completion(teams)
}

Related

How to Implement pagination in table view cell

My app retrieves json from the newsAPI.com . When I look at the json returned from the web service , it shows 2000 values however it returns 20 values loaded into my tableview controller. How do I increase the value so that when the user scrolls down the table view, they are presented with more values loaded into the table view controller?
class LatestNewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let newsData = Articles() //Model object
let urlRequest = "https://newsapi.org/v2/everything?q=coronavirus&apiKey=d32071cd286c4f6b9c689527fc195b03" //Website API
var urlSelected = ""
var articles: [Articles]? = [] // holds array of Articles data
var indexOfPageToRequest = 1
#IBOutlet weak var table_view: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
table_view.cellLayoutMarginsFollowReadableWidth = true
navigationController?.navigationBar.prefersLargeTitles = true
retriveData( )
}
func retriveData( )->Int{
guard let aritcleUrl = URL(string: urlRequest) else { //send a request to the server
return n
}
let request = URLRequest(url: aritcleUrl)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in //collects content from website
if error != nil { // checks if content is available
print(error ?? 0)
return
}
if let data = data { // converts data to an array of Article objects
self.articles = self.parseData(data: data)
}
})
task.resume()
return n
}
func parseData(data:Data)-> [Articles] {
var articles: [Articles]? = [] // holds parsed data
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
let jsonArticles = jsonResult?["articles"] as? [AnyObject] ?? [] // gets first head of json file and converts it to dictionary
for jsonArticle in jsonArticles{ // captures data and stores it in the model object
let article = Articles()
article.author = jsonArticle["author"] as? String
article.title = jsonArticle["description"] as? String
article.publishedAt = jsonArticle["publishedAt"] as? String
article.urlImage = jsonArticle["urlToImage"] as? String
article.urlWebsite = jsonArticle["url"] as? String
articles?.append(article) //put article data in the array
}
print(jsonArticles)
DispatchQueue.main.async {
if(articles!.count > 0)
{
self.table_view.reloadData()
}
}
} catch {
print("Nothing my guy\(error)")
}
return articles ?? [] // returns an array of articles
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell
cell.authorName.text = articles?[indexPath.row].author
cell.headLine.text = articles?[indexPath.row].title
cell.newsImage.downloadImage(from:(self.articles?[indexPath.item].urlImage ?? "nill"))
cell.timePublication.text = articles?[indexPath.row].publishedAt
return cell
}
[1]: https://i.stack.imgur.com/OY5G5.png
First, I would check the constraints of the table view, because this is a common issue (usually 0,0,0,0)
And also I would check the 'scrolling enabled' in the Attribute inspector and 'reuse Identifier'

Swift 3, how to parse first and show it on next TableViewController

I am really new to developing iOS apps. So I also apologize in advance if my coding is not close to being optimal or good written...
I am trying to create fairly simple app only for showing retrieving and showing data, but I hit a bump which I am trying to solve it for past few days, but I need help...
So the whole functionality of the app is like this: when opened(displying viewcontroller with textfield and button), user should enter username and push button. After button is pushed app should then do 2 things in next order:
combine certain URL address with entered username, retrieve data
(what kind of data, depends on given username - I gave few examples
on the bottom of that post) and pass them to next
tableviewcontroller
display tableviewcontroller and show parsed data.
But, this does not happen, what I noticed is, that my app opens new tableviewconotrller first, and after tableviewcontroller is open, it parses data, which causes that my table has no data (but I can see that data has been parsed, using print())
I am using Swift 3.
ViewController with textfield and button for "login":
import UIKit
class ViewController: UIViewController {
var zavodi = [[String]]()
#IBOutlet weak var uporabnik: UITextField!
#IBAction func vstop(_ sender: Any) {
self.parse { (completed) in
if (completed){
let zavodiView = self.storyboard?.instantiateViewController(withIdentifier: "zavodiController") as! ZavodiController
zavodiView.niz = self.uporabnik.text!
zavodiView.zavodi = self.zavodi
self.navigationController?.pushViewController(zavodiView, animated: true)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title="Vstop"
}
func parse( completion: #escaping (_ completed: Bool)-> () ){
let uporabnikIme = uporabnik.text!
//parsing
let shramba = UserDefaults.standard
let zavodiUrl = "https://oaza.rrc.si/eZaporiMobi/kapStSta/read?pUporabniskoIme="+uporabnikIme;
var zavodiRequest = URLRequest(url: URL(string: zavodiUrl)!)
zavodiRequest.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: zavodiRequest) { (data, response, error) in
if (error != nil) {
print("Error")
}
else {
var zavodiTemp = [Zavod]()
do {
let fetchedData = try JSONSerialization.jsonObject(with: data!) as! NSArray
//print(fetchedData)
zavodiTemp.removeAll()
for najdenZavod in fetchedData {
let vsakZavod = najdenZavod as! [String : Any]
let zavodId = vsakZavod["zaiId"] as! Int
let naziv = vsakZavod["kratekNaziv"] as! String
let ureditev = vsakZavod["ureditev"] as! Int
let zasedenost = vsakZavod["zasedenost"] as! String
let kapaciteta = vsakZavod["kapaciteta"] as! Int
let stStanje = vsakZavod["stStanje"] as! Int
let naBegu = vsakZavod["naBegu"] as! Int
let prekinitev = vsakZavod["prekinitev"] as! Int
zavodiTemp.append(Zavod(zavodId: zavodId, naziv: naziv, ureditev: ureditev, zasedenost: zasedenost,kapaciteta: kapaciteta, stStanje: stStanje, naBegu: naBegu, prekinitev: prekinitev))
}
zavodiTemp = zavodiTemp.sorted(by: {$0.ureditev < $1.ureditev})
self.zavodi.removeAll()
for e in zavodiTemp {
var temp = [String]()
temp.append(String(e.zavodId)) //0
temp.append(e.naziv) //1
temp.append(String(e.ureditev)) //2
temp.append(e.zasedenost) //3
temp.append(String(e.kapaciteta)) //4
temp.append(String(e.stStanje)) //5
temp.append(String(e.naBegu)) //6
temp.append(String(e.prekinitev)) //7
self.zavodi.append(temp)
}
let steviloZavodov = self.zavodi.count
shramba.set(self.zavodi, forKey:"zavodi")
shramba.set(steviloZavodov, forKey:"steviloZavodov")
var s = [[String]]()
s = shramba.array(forKey: "zavodi") as! [[String]]
for e in s{
print(e[2]+" "+e[1])
}
}
catch {
print()
}
}
}
task.resume()
completion(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
class Zavod {
var zavodId : Int
var naziv : String
var ureditev : Int
var zasedenost : String
var kapaciteta : Int
var stStanje : Int
var naBegu : Int
var prekinitev : Int
init(zavodId : Int, naziv : String, ureditev : Int, zasedenost : String, kapaciteta : Int, stStanje : Int, naBegu : Int, prekinitev : Int) {
self.zavodId = zavodId
self.naziv = naziv
self.ureditev = ureditev
self.zasedenost = zasedenost
self.kapaciteta = kapaciteta
self.stStanje = stStanje
self.naBegu = naBegu
self.prekinitev = prekinitev
}
}
}
TableViewController where should parsed data be displayed:
import UIKit
class ZavodiController: UITableViewController {
var niz = ""
var zavodi = [[String]]()
override func viewDidLoad() {
super.viewDidLoad()
print(niz)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("število zavodov"+String(self.zavodi.count))
return self.zavodi.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "zavodCelica", for: indexPath) as! ZavodCelica
cell.nazivZavoda.text = self.zavodi[indexPath.row][1]
cell.kapaciteta.text = self.zavodi[indexPath.row][4]
cell.zasedenost.text = self.zavodi[indexPath.row][3]
cell.stStanje.text = self.zavodi[indexPath.row][5]
cell.naBegu.text = self.zavodi[indexPath.row][6]
cell.prekinitev.text = self.zavodi[indexPath.row][7]
return cell
}
}
I also tried to use UserDefaults, but it just seems that tableviewcontroller just simply gets loaded before actual parsing is done.
For usernames, you can use:
-"manj", returns 1 record
-"mref", returns 3 records
-"mmli", returns 14 records
I would really appreciate any help.
There can be a lot of ways to achieve this. Reloading the table is also a fix. But to be very accurate with the data your should wait for the function completion before moving to the next screen. Look at the code
func parse()( completion: #escaping (_ completed: Bool)-> () ){
// parse logic goes in here
// after the processing finishes return true like following
completion(true) // you can also have logic to return failures.
}
This will be called like
self.parse { (completed) in
if (completed){
let zavodiView = storyboard?.instantiateViewController(withIdentifier: "zavodiController") as! ZavodiController
zavodiView.niz = uporabnik.text!
zavodiView.zavodi = self.zavodi
navigationController?.pushViewController(zavodiView, animated: true)
}
}
Afetr appending data to the table array add this
DispatchQueue.main.async {
self.tableview.reloadData()
}

TableView is not loading any JSON data Swift 4

I have spent about three weeks trying to figure this out. I can get the section title to view, but none of the JSON data is showing. When I do a standard "array" contained in the file, it displays.
I have followed every tip and trick out there and I am stuck.
I think this may have something to do with AnyObject and String, but I am missing something. Please see my code below:
import UIKit
import Alamofire
import SwiftyJSON
class UserTableViewCell: UITableViewCell {
#IBOutlet weak var userFirstname: UILabel!
#IBOutlet weak var userLastname: UILabel!
}
class Profile2VC: UITableViewController {
#IBOutlet var userTable: UITableView!
var usertitles = ["First Name", "Last Name", "Email", "Mobile Number"]
var userinfo = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
let defaultValues = UserDefaults.standard
let URL_USER_LOGIN = "https://www.myapp.com/myphp.php"
let userid = "13"
let parameters: Parameters=["id":coolid]
Alamofire.request(URL_USER_LOGIN, method: .get, parameters:
parameters).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
if let userData = swiftyJsonVar["user"].arrayObject {
self.userinfo = userData as! [[String:AnyObject]]
//debugPrint(userData)
}
if self.userinfo.count > 0 {
self.userTable.reloadData()
}
}
}
self.userTable.reloadData()
// Uncomment the following line to preserve selection between
presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the
navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userinfo.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection
section: Int) -> String? {
return "Section \(section)"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell",
for: indexPath) as! UserTableViewCell
//let userTitles = usertitles[indexPath.row]
let userInfo = userinfo[indexPath.row]
cell.userFirstname?.text = userInfo["first_name"] as? String
cell.userLastname?.text = userInfo["last_name"] as? String
//cell.imageView?.image = UIImage(named: fruitName)
//cell.textLabel?.text = usertitles[indexPath.row]
return cell
}
}
First of all you need to reload your table view in main queue. Check below code:
DispatchQueue.main.async {
self.userTable.reloadData()
}
And you are reloading it multiple times which is not good so Remove unwanted reload code and you final code will be:
Alamofire.request(URL_USER_LOGIN, method: .get, parameters: parameters).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar)
if let userData = swiftyJsonVar["user"].arrayObject {
self.userinfo = userData as! [[String:AnyObject]]
//debugPrint(userData)
}
if self.userinfo.count > 0 {
DispatchQueue.main.async {
self.userTable.reloadData()
}
}
}
}
//self.userTable.reloadData() //Remove this code
And once your API call done, Make sure debugPrint(userData) is printing some data and then when you are reloading userTable put a breakpoint in cellForRowAt and confirm that it's calling.
Then if its calling and data is there from server, You are good to go.
But if cellForRowAt method didn't called then you need to check your userTable DataSource and Delegate if it's correctly connected or not.
Try this code :
let API = URL(string:"http://www.myapp.com/myphp.php")
let request = URLRequest(url:API!)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
if String(data: data, encoding: String.Encoding.utf8) != nil {
let data = data
let json = try? JSONSerialization.jsonObject(with: data, options: [])
let jsonData = json as! [[String:Any]]
DispatchQueue.main.sync {
let user = jsonData.flatMap { $0["user"] as? String }
print(user)
self.annocumentTableView.reloadData()
}
}
}
})
task.resume()

Array doesn't save

Getting a JSON object from a rest web service I get the data from the object and I want to show it in a tableview.
class TableViewController1: UITableViewController {
var nomProduit = ["ok"]
var prixProduit = [""]
var vt1 : String?
var vt2 : String?
var i : Int!
var compteur1:Int!
var resultat1:NSArray?
var x : AnyObject?
override func viewDidLoad() {
super.viewDidLoad()
// \(detectionString)
let str:String = "http://vps43623.ovh.net/yamoinscher/api/products/6194005492077"
let url = NSURL(string: str)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers)
self.resultat1 = jsonResult["meme_categorie"] as? NSArray
self.compteur1 = self.resultat1!.count
print(self.compteur1!)
//self.value = (compteur1 as? Int)!
for self.i=0 ; self.i < self.compteur1! ; self.i = self.i+1 {
if let aStatus = self.resultat1![self.i] as? NSDictionary{
self.vt1 = aStatus["libelle_prod"]! as? String
self.nomProduit.append(self.vt1!)
self.vt2 = aStatus["prix"]! as? String
self.prixProduit.append(self.vt2!)
//print(self.nomProduit[self.i])
}
}
} catch {
print("JSON serialization failed")
}
}
}
task.resume()
}
Then My problem is that this array stays nil:
self.prixProduit.append(self.vt2!)
here is the rest of my code
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 17
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! customCell1
// cell.PrixSim.text = nomProduit[indexPath.row]
print(self.nomProduit[0])
return cell
}
First of all use a custom struct for the category objects, it makes things so much easier.
At the beginning of TableViewController1
class TableViewController1: UITableViewController {
declare this struct
struct Produit {
var id : String
var prix : String
var title : String
}
and a data source array (forget all your other properties / variables)
var produits = [Produit]()
In viewDidLoad get the data, populate the data source array and reload the table view on the main thread.
This code uses Swift native collection types
override func viewDidLoad() {
super.viewDidLoad()
// \(detectionString)
let str = "http://vps43623.ovh.net/yamoinscher/api/products/6194005492077"
let url = NSURL(string: str)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if let urlContent = data {
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(urlContent, options: [])
if let jsonResult = jsonObject as? [String:AnyObject] {
if let memeCategorie = jsonResult["meme_categorie"] as? [[String:String]] {
for categorie in memeCategorie {
if let prix = categorie["prix"], title = categorie["libelle_prod"], id = categorie["id"] {
self.produits.append(Produit(id: id, prix: prix, title: title))
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
} catch {
print("JSON serialization failed", error)
}
} else if let connectionError = error {
print("connection error", connectionError)
}
}
task.resume()
}
In numberOfRowsInSection return the actual number of items rather than a hard-coded number.
You can omit numberOfSectionsInTableView since the default value is 1.
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return produits.count
}
In cellForRowAtIndexPath get the item by index path and assign the values to your labels (or whatever). For now the values are just printed out.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell1", forIndexPath: indexPath) as! customCell1
let produit = produits[indexPath.row]
print(produit.id, produit.title, produit.prix)
return cell
}
}

Parsing JSON into tableview

I am receiving a JSON file from a remote server and I can display the result in a label. The JSON data is working fine when I call function processJSONData() and the tableview works fine with a simple array. How can I incorporate both to display the result from the JSON file in the tableview? Kindly look at the code below and edit. Many thanks:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var countryLabel: UILabel!
#IBOutlet weak var capitalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//processJSONData()
self.myTableView.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.myTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func processJSONData(){
let urlPath = "http://dubaisinan.host22.com/service1.php"
let url : NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url,completionHandler: {(data, respose, error) -> Void in
if error != nil {
println(error)
}
else {
self.abc(data)
}
})
task.resume()
}
func abc(data:NSData)
{
var parseError: NSError?
let result:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);
if(parseError == nil){
if let dictResult = result as? NSArray{
dispatch_async(dispatch_get_main_queue()) {
self.countryLabel.text = dictResult[2]["Capital"] as? String
}
}
}
}
#IBOutlet weak var myTableView: UITableView!
var items = ["One","Two", "Three","Four"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.myTableView
.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
}
I don't see you assign your parsing result to global "items" and reload tableview with new data anywhere.
could be done here
if let dictResult = result as? NSArray{
self.items = dictResult
self.myTableView.reloadData()
///the rest of the code
}
You have to save the JSON data into a class-level variable, which you will define outside of any function, similar to how you defined "items". Assuming you have a list of countries with the capital of each, this might look like so:
var countryAndCapitalData = [(country: String, capital: String)]()
This could be improved by first defining a struct to contain your data:
struct CountryInfo
{
name: String
capital: String
init(name:String, capital:String)
{
self.name = name
self.capital = capital
}
}
which lets you define your data array as an array of CountryInfo:
var countryAndCapitalData = [CountryInfo]()
Then in your "abc" function (which I insist you rename to something like processCountryData), store the pairs of country name + capital name strings in countryAndCapitalData. For example:
countryAndCapitalData.append(CountryInfo(countryName, capitalName))
Use a For loop to loop through values in dictResult. Creating countryName and capitalName depends on the structure of your JSON, but from your example it might look like this:
for countryDictionary in dictResult[2]
{
if let countryName = countryDictionary["country"], let capitalName = countryDictionary["capital"]
{
countryAndCapitalData.append(CountryInfo(countryName, capitalName))
}
}
Then in tableView.cellForRowAtIndexPath, populate the cell label(s) with countryAndCapitalData[indexPath.row].name and countryAndCapitalData[indexPath.row].capital.
And finally, be sure to reload the table after the loop (thanks Eugene):
dispatch_async(dispatch_get_main_queue()) {
self.myTableView.reloadData()
}
Apologies for any compilation errors, as I'm typing this from a Windows machine.
You should update your items property in abc method call and then refresh the table:
func abc(data: NSData) {
// Do something with data
items = .. // processed data
}
var items: [String]? {
didSet {
NSOperationQueue.mainQueue.addOperationWithBlock {
self.tableView.reloadData()
}
}
}

Resources