table view cannot be displayed on device - ios

I am developing iOS app where I want to display table content one my device.but unable fetch and display...but contents are being displayed on console view.
I am using json getmethod() to fetch the details
also using view controller and view table and swift language
import UIKit
class UpdateSheetManagementViewController:
UIViewController, UITableViewDelegate, UITableViewDataSource, WebserviceDelegate {
//var FinalArray = [[String:Any]]()
// class func instantiateFromStoryboard() -> UpdateSheetManagementViewController {
// let storyboard = UIStoryboard(name: "Management", bundle: nil)
// return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! UpdateSheetManagementViewController
// }
#IBOutlet weak var managementTableView: UITableView!
var controllerType : String!
var array = [[String : Any]]()
override func viewDidLoad() {
super.viewDidLoad()
title = controllerType
updatesheetWebserviceCall()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// updatesheetWebserviceCall()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 320.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = tableView.dequeueReusableCell(withIdentifier: "UpdateSheetManagementTableViewCell", for: indexPath) as! UpdateSheetManagementTableViewCell
let cellIdentifier : String = "UpdateSheetManagementTableViewCell";
let cell : UpdateSheetManagementTableViewCell =
tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! UpdateSheetManagementTableViewCell
let dict = array[indexPath.section]
cell.classname.text = dict["Cls_Name"] as? String
cell.dateFrom.text = dict["Date_From"] as? String
cell.date_To.text = dict["Date_To"] as? String
cell.downloadButton.tag = indexPath.row
cell.downloadButton.addTarget(self, action: #selector(onDownloadButtonClicked(button:)), for: .touchUpInside)
return cell
}
func onDownloadButtonClicked(button : UIButton) {
let postion = button.tag
let data = array[postion]
let attachment = data["Attachment"] as? String
if(attachment != nil && attachment!.characters.count > 0){
let userid = UserDefaults.standard.string(forKey: USER_ID)
let finalString = "https://skillskool.mycit.co.in/PagesParentApp/Today-ClassNotes.aspx?FilePath=" + attachment! + "&UserId=" + userid! + "&PageName=UpdateSheet"
let url = URL(string: finalString)
if(url != nil){
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
}
func updatesheetWebserviceCall() {
let str = ""
let webClass = WebserviceClass()
webClass.delegate = self
webClass.fireRequest(functionName: "MgmtUpdateSheet.php", requestString: str, view: view)
}
func webserviceDidFinishWith(response: [String : Any], functionName: String) {
parseUpdateSheetWebservice(response: response)
}
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
// managementTableView.reloadData()
}
}
}

Add managementTableView.reloadData() after updating the data and make sure to set the delegate and datasource in either view controller or storyboard

Set tableview delegate and datasource in viewDidLoad and reload tableview in web service response.
// set tableview delegate and datasource in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
title = controllerType
managementTableView.dataSource = self
//managementTableView.delegate = self
updatesheetWebserviceCall()
}
// reload tableview upon web service response
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
self.managementTableView.reloadData()
/*
// or reload table using main queue, if you web service operation is in background queue
DispatchQueue.main.async {
self.managementTableView.reloadData()
}
*/
}
}

In the beginning, you need to set tableview dataSource and delegate and after loading data you also need to reload data.
self.managementTableView.delegate = self;
self.managementTableView.datasource = self;
Reload data:
self.array.append(contentsOf: arr!)
self.managementTableView.reloadData()

You have to set in viewDidLoad
managementTableView.dataSource = self
and un comment managementTableView.reloadData()
func parseUpdateSheetWebservice(response : [String : Any]) {
let arr = response["homework"] as? [[String : Any]]
if(arr != nil){
// array.removeAll()
self.array.append(contentsOf: arr!)
DispatchQueue.main.async {
managementTableView.reloadData() }
}
}

I think delegate and datasource connections are missed, please add the following code in viewDidLoad function:
self.managementTableView.delegate = self;
self.managementTableView.dataSource = self;

Related

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()
}

Load images from API

I'm creating an e-commerce app with (Moltin.com) SDK, I set every thing well as it shown in the documentation but now I need to load multi images of single product in table view with custom cell, I set the shown code below and all I can get is a single image my app ignore load the other images view controller code is
class vc: UIViewController , UITableViewDelegate, UITableViewDataSource {
var productDict:NSDictionary?
#IBOutlet weak var tableview: UITableView!
fileprivate let MY_CELL_REUSE_IDENTIFIER = "MyCell"
fileprivate var productImages:NSArray?
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
Moltin.sharedInstance().product.listing(withParameters: productDict!.value(forKeyPath: "url.https") as! [String : Any]!, success: { (response) -> Void in
self.productImages = response?["result"] as? NSArray
self.tableview?.reloadData()
}) { (response, error) -> Void in
print("Something went wrong...")
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if productImages != nil {
return productImages!.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: MY_CELL_REUSE_IDENTIFIER, for: indexPath) as! MyCell
let row = (indexPath as NSIndexPath).row
let collectionDictionary = productImages?.object(at: row) as! NSDictionary
cell.setCollectionDictionary(collectionDictionary)
return cell
}
and my custom cell code is
class MyCell: UITableViewCell {
#IBOutlet weak var myImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setCollectionDictionary(_ dict: NSDictionary) {
// Set up the cell based on the values of the dictionary that we've been passed
// Extract image URL and set that too...
var imageUrl = ""
if let images = dict.value(forKey: "images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String
}
}
myImage?.sd_setImage(with: URL(string: imageUrl))
}
Can anyone show me where is the issue that doesn't let me get all the images of my product?
I'm using SWIFT 3, with XCode
In the code below you are always getting one URL from images array (firstObject).
if let images = dict.value(forKey: "images") as? NSArray {
if (images.firstObject != nil) {
imageUrl = (images.firstObject as! NSDictionary).value(forKeyPath: "url.https") as! String
}
}
myImage?.sd_setImage(with: URL(string: imageUrl))
If I understand correctly you should get every image in images array by the indexPath.row of your tableView.
For example add new parameter to method like this:
func setCollection(with dict: NSDictionary, and index: Int) {
// Set up the cell based on the values of the dictionary that we've been passed
// Extract image URL and set that too...
var imageUrlString = ""
if let images = dict.value(forKey: "images") as? Array<NSDictionary>, images.count >= index {
guard let lImageUrlString = images[index]["url.https"] else { return }
imageUrlString = lImageUrlString
}
guard let imageURL = URL(string: imageUrl) else { return }
myImage?.sd_setImage(with: imageURL)
}
Than when call this method in cellForRow just add indexPath.row to the second param.
But if you want show multiple images in one cell you should add more imageViews to the custom cell or use UICollectionView.
Just ping me if I don't understand you clear.

Swift: Multiple Custom TableViewCells from XIB files

I am following this tutorial from Jared Davidson to implement multiple CustomTableViewCells with XIB files in my app. I have these files in my Xcode project:.
I have a TextElement: and
I have an ImageElement:
I want to test this with offline data to implement Firebase after this is working. This is my Home.swift data struct:
import Foundation
import FirebaseDatabase
struct Home {
var key:String!
let itemRef:FIRDatabaseReference?
var userUID:String!
var user:String!
// Home Element Cell Content
var elementSortNumber:Int!
var elementCellType:String!
var referenceElementID:String!
var databaseVersion:String!
init (key:String = "",
uid:String,
user:String,
elementSortNumber:Int,
elementCellType:String,
referenceElementID:String,
databaseVersion:String) {
// General (Security tracking)
self.key = key
self.itemRef = nil
self.userUID = uid
self.user = user
// Home Element Cell Content
self.elementSortNumber = elementSortNumber
self.elementCellType = elementCellType
self.referenceElementID = referenceElementID
}
init (snapshot:FIRDataSnapshot) {
// General (Security tracking)
key = snapshot.key
itemRef = snapshot.ref
if let addedByUser = snapshot.value as? NSDictionary, let _temp = addedByUser["User"] as? String {
user = _temp
} else {
user = ""
}
// Home Element Cell Content
if let homeElementSortNumber = snapshot.value as? NSDictionary, let _temp = homeElementSortNumber["Title"] as? Int {
elementSortNumber = _temp
} else {
elementSortNumber = 50
}
if let homeElementCellType = snapshot.value as? NSDictionary, let _temp = homeElementCellType["Content"] as? String {
elementCellType = _temp
} else {
elementCellType = ""
}
if let homeElementID = snapshot.value as? NSDictionary, let _temp = homeElementID["Ref Element ID"] as? String {
referenceElementID = _temp
} else {
referenceElementID = ""
}
if let textDatabaseVersion = snapshot.value as? NSDictionary, let _temp = textDatabaseVersion["DB Version"] as? String {
databaseVersion = _temp
} else {
databaseVersion = ""
}
}
}
This is the code of my TableViewController:
import UIKit
class HomeTableViewController: UITableViewController {
var arrayOfCellData = [Home]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
arrayOfCellData =
[Home(key: "",
uid:"",
user:"",
elementSortNumber:1,
elementCellType:"TextElement",
referenceElementID:"123ABC",
databaseVersion:"1"),
Home(key: "",
uid:"",
user:"",
elementSortNumber:1,
elementCellType:"ImageElement",
referenceElementID:"QWERTZ",
databaseVersion:"1"),
Home(key: "",
uid:"",
user:"",
elementSortNumber:1,
elementCellType:"TextElement",
referenceElementID:"XYZ789",
databaseVersion:"1")]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// If I return 1 the app crashes and if I comment this function it also crashes.
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayOfCellData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if arrayOfCellData[indexPath.row].elementCellType == "TextElement" {
let textElementCell = Bundle.main.loadNibNamed("TextElementTableViewCell", owner: self, options: nil) as! TextElementTableViewCell
textElementCell.textElementTitleLabel.text = arrayOfCellData[indexPath.row].referenceElementID
return textElementCell
}
else if arrayOfCellData[indexPath.row].elementCellType == "ImageElement" {
let imageElementCell = Bundle.main.loadNibNamed("ImageElementTableViewCell", owner: self, options: nil) as! ImageElementTableViewCell
imageElementCell.imageElementImageView.image = UIImage(named: "placeholder")
return imageElementCell
}
else {
let textElementDefaultCell = Bundle.main.loadNibNamed("TextElementTableViewCell", owner: self, options: nil) as! TextElementTableViewCell
textElementDefaultCell.textElementTitleLabel.text = arrayOfCellData[indexPath.row].referenceElementID
return textElementDefaultCell
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if arrayOfCellData[indexPath.row].elementCellType == "TextElement" {
return 116
}
else if arrayOfCellData[indexPath.row].elementCellType == "ImageElement" {
return 275
}
else {
return 116
}
}
}
This is the problem: The simulator is empty as you can see in this image Why? How can I fix that?
I would really appreciate some help. Thank you.
Register the xib files as below in viewdidload:
tableView.register(UINib(nibName: "TextElementTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "TextElementTableViewCellIdentifier")
Then in cellForRowIndex path:Access cell using their identifier
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "TextElementTableViewCellIdentifier", for: indexPath) as! TextElementTableViewCell

How do I extract a variable from a UITable DidSelectAtRow?

I have an instance where a user picks from a UITable. The selected record has a name and an id associated with it.
At the moment to verify the name and id are being correctly reported I am using
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)
Country(name: Optional("England"), countryId: Optional("5"))
I want to be able to store that countryId in a variable so I can repopulate my UITable with data (Football Divisions) that match the countryId '5'
How do I do this?
This is my full script:
import UIKit
class PickTeamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var teamsTableView: UITableView!
var pickedCountryID: Int?
var selectedCellCountryTitle: String?
var cellCountryId: Int?
struct Country {
var name: String?
var countryId: String?
init(_ dictionary: [String : String]) {
self.name = dictionary["name"]
self.countryId = dictionary["id"]
}
}
struct Divisions {
var divisionName: String?
var divisionId: String?
init(_ dictionary: [String : String]) {
self.divisionName = dictionary["name"]
self.divisionId = dictionary["country_id"]
}
}
struct Teams {
var teamName: String?
var newTeamId: String?
init(_ dictionary: [String : String]) {
self.teamName = dictionary["name"]
}
}
struct TeamId {
var newTeamId: String?
init(_ dictionary: [String : String]) {
self.newTeamId = dictionary["id"]
}
}
var newCountries = [Country]()
var newDivisions = [Divisions]()
var newTeams = [Teams]()
var newTeamId = [TeamId]()
override func viewDidAppear(_ animated: Bool) {
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "GET";
let task = URLSession.shared.dataTask(with: myUrl!) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
print (json)
if let arr = json?["countries"] as? [[String:String]] {
self.newCountries = arr.flatMap { Country($0) }
self.teamsTableView.reloadData()
}
if let arr = json?["divisions"] as? [[String:String]] {
self.newDivisions = arr.flatMap { Divisions($0) }
}
if let arr = json?["teams"] as? [[String:String]] {
self.newTeams = arr.flatMap { Teams($0) }
}
self.teamsTableView.reloadData()
} catch{
print(error)
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.newCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let country = newCountries[indexPath.row]
let cell = UITableViewCell()
cell.textLabel?.text = country.name
cell.textLabel?.font = UIFont(name: "Avenir", size: 12)
cell.textLabel?.textColor = UIColor.black
cell.backgroundColor = UIColor.white
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
cellCountryId = indexPath.row
// print (self.newCountries[cellCountryId!])
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)
}
override func viewDidLoad() {
super.viewDidLoad()
self.teamsTableView.delegate = self
self.teamsTableView.dataSource = self
// Do any additional setup after loading the view.
}
}
As discussed in the comments you should use another view controller to show the details. In didSelectRowAtIndexPath method take out the selected country from newCountries array and pass it to the DetailViewController.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let countryDetailsVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryDetailsViewController") as! DetailViewController
countryDetailsVC.country = selectedCountry
present(countryDetailsVC, animated: true, completion: nil)
}
Now that you have the country Struct you can show its details in the DetailViewController.
Your table is populated from the array newCountries. So, to replace the contents of the table, you would need to replace the contents of newCountries and reload the table.
But that is not a very wise strategy. It would be better to show a different view controller with a different table and a different data array.

return data in DetailTableView (swift)

In my app I have two table views. The first table view has a set number of cells. These cells will always be the same and will never change The above table view will always have the 4 cells and never more. On my server I have my API which has routes for each of these cells.
For example:
GET - myAPI/Air
GET - myAPI/history
GET - myAPI/train
GET - myAPI/taxi
And each routes send backs different data
mainTablewView:
import UIKit
enum NeededAPI {
case Air
case History
case Train
case Taxi
}
class mainTableViewController : UITableViewController {
struct WeatherSummary {
var id: String
}
var testArray = NSArray()
var manuArray = NSArray()
// Array of sector within our company
var selectSector: [String] = ["Air", "History","Train","Taxi"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 80.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.selectSector.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("sectorList", forIndexPath: indexPath)
// Configure the cell...
if selectSector.count > 0 {
cell.textLabel?.text = selectSector[indexPath.row]
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "AirSegue"){
if let destination = segue.destinationViewController as? AirTableViewController {
let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
if let row:Int = indexPath.row {
destination.apiThatNeedsToBeCalled = .Air
}
}
}
if (segue.identifier == "HistorySegue"){
if let destination = segue.destinationViewController as? HistoryTableViewController {
let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
if let row:Int = indexPath.row {
destination.apiThatNeedsToBeCalled = .History
}
}
}
if (segue.identifier == "TrainSgue"){
if let destination = segue.destinationViewController as? TrainTableViewController {
let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
if let row:Int = indexPath.row {
destination.apiThatNeedsToBeCalled = .Train
}
}
}
if (segue.identifier == "TaxiSegue"){
if let destination = segue.destinationViewController as? TaxiTableViewController {
let indexPath:NSIndexPath = self.tableView.indexPathForSelectedRow!
if let row:Int = indexPath.row {
destination.apiThatNeedsToBeCalled = .Taxi
}
}
}
}
}
and Post
import Foundation
class Post : CustomStringConvertible {
var userId:Int
var title: String
init(userid:Int , title:String){
self.userId = userid
self.title = title
}
var description : String { return String(userId) }
}
When user selects cell you set the correct value for the apiThatNeedsToBeCalled. Once you do this, code inside the didSet will get executed and it should call the function which calls the appropriate API.
to other tableView :
import UIKit
class AirTableViewController: UITableViewController {
var postCollection = [Post]()
var apiThatNeedsToBeCalled:NeededAPI = .Air {
didSet {
//check which API is set and call the function which will call the needed API
AirLine()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var apiThatNeedsToBeCalled:NeededAPI = .Air {
didSet {
//check which API is set and call the function which will call the needed API
AirLine()
}
}
func AirLine(){
let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
NSURLSession.sharedSession().dataTaskWithURL(url!){[unowned self] (data , respnse , error) in
if error != nil{
print(error!)
}else{
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var newPost = Iduser(id: 0)
for posts in json {
let postObj = Post(userid:posts["userId"] as! Int,title: posts["title"] as! String)
self.postCollection.append(postObj)
}
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
}catch let error as NSError{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
print(error.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON:\(jsonStr)")
dispatch_async(dispatch_get_main_queue()) {
let alert = UIAlertController(title: "Alert", message: "Oops! Wrong Details, Try Again", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.postCollection.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AirCell", forIndexPath: indexPath)
// Configure the cell...
// cell.textLabel?.text = "test"
let weatherSummary = postCollection[indexPath.row]
cell.textLabel?.text = String(weatherSummary.userId)
cell.detailTextLabel?.text = weatherSummary.title
return cell
}
}
mainTableView and Air cell is Ok but when that selected other return The same information Air cell?
Perhaps I'm just missing it, but I can see your creation of the NSURLSession looks fine, but I don't see where you're calling .resume() on that once you've created it. If you don't call .resume() it'll never even perform that URLSession at all. Check the discussion here.

Resources