How do I extract a variable from a UITable DidSelectAtRow? - ios

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.

Related

I am showing data like Expendable Tableview

I am showing data like expendable tableview with a header section. Header is showing fine. but When I am showing rows . (Like in a product 5 addons then data is showing like in expendable Tableview Every Row with a Same Type Name Header). I am attaching screenshot. What type of data is showing.
Image Data Showing Like : https://imgur.com/a/JXqUbJD
I am attaching I current code which I am using . I already tried too many times but it is not working fine.
import UIKit
import Reachability
import Alamofire
class ExpendableTableview: UIViewController, UITableViewDelegate, UITableViewDataSource, CollapsibleTableViewHeaderDelegate {
#IBOutlet weak var tableview: UITableView!
var catid:Int!
var reachability = Reachability()!
var arraySubCategory = [structSubCategory]()
struct structSubCategory {
var id:Int
var minimum_people:String
var title:String
var package_price:String
var package_image:String
var package_label:String
var categoryId:Int
// var addons: [cateringAddOns]
// var collapsed: Bool
}
var arraySection = [section]()
struct section
{
var title: String
var addons : [cateringAddOns]
var collapsed: Bool
}
var arrayCateringAddOns = [cateringAddOns]()
struct cateringAddOns {
var no_of_items:Int
var add_on_type:Int
var package_item:String
var upgrade_price:String
}
var NormalArr = ["Balance", "Sales", "Order Status", "Social Media Complaints", "Logout"]
override func viewDidLoad() {
super.viewDidLoad()
print(catid)
SubCateringAPI(cateringId: catid)
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return arraySection.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arraySection[section].collapsed ? 0 : arraySection[section].addons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellRID") as! ExpendableAddOnsCell
let item : cateringAddOns = arraySection[indexPath.section].addons[indexPath.row]
cell.lblAddon.text = item.package_item
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reuseIdentifier: "header")
header.titleLabel.text = arraySection[section].title
header.arrowLabel.text = ">"
header.setCollapsed(arraySection[section].collapsed)
header.section = section
header.delegate = self
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {
let collapsed = !arraySection[section].collapsed
// Toggle collapse
arraySection[section].collapsed = collapsed
header.setCollapsed(collapsed)
tableview.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
// func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return arraySection[section].title
// }
//
#IBAction func btnDismiss(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func SubCateringAPI(cateringId:Int)
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
SwiftLoader.show(animated: true)
let url = BaseUrl + ViewController.sharedInstance.subCatering + "cateringId=\(cateringId)"
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
let json = response.result.value
print(json)
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
for alldata in data!
{
let id = (alldata as AnyObject).object(forKey: "id") as! Int
let minimum_people = (alldata as AnyObject).object(forKey: "minimum_people") as! String
let title = (alldata as AnyObject).object(forKey: "title") as! String
let package_price = (alldata as AnyObject).object(forKey: "package_price") as! String
let package_image = (alldata as AnyObject).object(forKey: "package_image") as! String
let package_label = (alldata as AnyObject).object(forKey: "package_label") as! String
let categoryId = (alldata as AnyObject).object(forKey: "categoryId") as! Int
let arr = structSubCategory(id: id, minimum_people: minimum_people, title: title, package_price: package_price, package_image: package_image, package_label: package_label, categoryId: categoryId)
self.arraySubCategory.append(arr)
}
for i in self.arraySubCategory
{
let id = i.categoryId
let title = i.package_label
self.cateringAddOndsAPI(adonsId: id, title: title)
}
SwiftLoader.hide()
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
alert(title: "", message: "Please Check Your Internet Connection")
}
}
func cateringAddOndsAPI(adonsId:Int, title: String)
{
if (reachability.connection == .wifi) || (reachability.connection == .cellular)
{
arraySection.removeAll()
arrayCateringAddOns.removeAll()
SwiftLoader.show(animated: true)
let url = BaseUrl + ViewController.sharedInstance.cateringAddOnds + "adonsId=\(adonsId)"
print(url)
Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default).responseJSON { response in
switch response.result {
case .success:
let json = response.result.value
print(json)
let code = (json as AnyObject).object(forKey: "code") as! Int
print(code)
if code == 200
{
let data = (json as AnyObject).object(forKey: "data") as? NSArray
for alldata in data!
{
let no_of_items = (alldata as AnyObject).object(forKey: "no_of_items") as! Int
let add_on_type = (alldata as AnyObject).object(forKey: "add_on_type") as! Int
let package_item = (alldata as AnyObject).object(forKey: "package_item") as! String
let upgrade_price = (alldata as AnyObject).object(forKey: "upgrade_price") as! String
let arr = cateringAddOns(no_of_items: no_of_items, add_on_type: add_on_type, package_item: package_item, upgrade_price: upgrade_price)
self.arrayCateringAddOns.append(arr)
let expandData = section(title: title, addons: [arr], collapsed: false)
self.arraySection.append(expandData)
}
self.tableview.reloadData()
SwiftLoader.hide()
}
else
{
}
case .failure:
print("error")
}
}
}
else
{
alert(title: "", message: "Please Check Your Internet Connection")
}
}
}
you should call override func prepareForReuse() inside the class CollapsibleTableViewHeader.
override func prepareForReuse() {
super.prepareForReuse()
//TODO: set default values
}
Could you provide code of CollapsibleTableViewHeader class?

How to check and delete duplicates values in TableView?

I have a database on Firebase and a tableview.
I have a list of brands, models, and year for motorcycles and I want to retrieve the list of brands on the tableview.
The problem is the DB has duplicates values. There is more than one motorcycle from Suzuki, there is more one models of SV 650, etc.
How can I check duplicates values, put it in a new array, and retrieve it in the tableview?
This is my TableViewController file:
import UIKit
import FirebaseAuth
import FirebaseDatabase
class SelectionMarqueViewController: UITableViewController {
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
loadMarques()
}
func loadMarques() {
var ref : DatabaseReference?
ref = Database.database(url: "https://myride-test.firebaseio.com/").reference()
ref?.observe(.childAdded, with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
let post = Post(MarqueText: MarqueText)
self.posts.append(post)
print(self.posts)
self.tableView.reloadData()
}
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath)
cell.textLabel?.text = posts[indexPath.row].Marque
return cell
}
}
And this one is the file with the Post func:
import Foundation
class Post {
var Marque: String
init(MarqueText: String) {
Marque = MarqueText
}
}
Here my Firebase Database:
Actually the tableview shows the complete list of brands in the DB, and so, many times the same brands.
On the DB and code:
"Marque" correspond to the brand.
You can implement Hashable
class Post : Hashable {
var marque: String
init(marqueText: String) {
marque = marqueText
}
// Equatable for contains
static func == (lhs:Post,rhs:Post) -> Bool {
return lhs.marque == rhs.marque
}
// Hashable for Set
var hashValue:Int {
return marque.hashValue
}
}
and use
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
let post = Post(MarqueText: MarqueText)
self.posts.append(post)
self.posts = Array(Set(self.posts))
print(self.posts)
self.tableView.reloadData()
}
Or simply
let marqueText = dict["Marque"] as! String
if !self.posts.map { $0.marqueText}.contains(marqueText) {
let post = Post(marqueText:marqueText)
self.posts.append(post)
self.tableView.reloadData()
}
Check and append if the marque is not available in the datasource of the tableview.
func appendMarqueAndReloadIfNeeded(_ marque: String) {
if self.posts.map({ $0.Marque }).contains(marque) {
// Do nothing
} else {
self.posts.append(Post(MarqueText: marque))
self.tableView.reloadData()
}
}
Then you call it inside observe:
///....
if let dict = snapshot.value as? [String: Any] {
let MarqueText = dict["Marque"] as! String
self.appendMarqueAndReloadIfNeeded(MarqueText)
}
///....

Get parent key in UITableview with firebase

I have my firebase database structured like this:
Snap (-KWLSAIh5WJvNJOkxBEr) {
beschrijving = "description";
image = "link to image";
title = "title";
}
Snap (-KWLSTak0H20X_2Qnanv) {
beschrijving = "description";
image = "link to image";
title = "title";
}
This is the code I am using to display this in a TableView:
import UIKit
import Firebase
class NieuwsTableViewController: UITableViewController {
var users = [UsersII]()
let cellId = "IdCell"
override func viewDidLoad() {
super.viewDidLoad()
fetchUser()
}
func fetchUser() {
Database.database().reference().child("Blog").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = UsersII(dictionary: dictionary)
self.users.append(user)
print(snapshot)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> lllTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let user = users.reversed()[indexPath.row]
cell.textLabel?.text = user.name
return cell as! lllTableViewCell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = users.reversed()[indexPath.row]
guard let beschrijving = message.beschrijving else {
return
}
guard let image = message.plaatje else {
return
}
guard let titel = message.name else {
return
}
UserDefaults.standard.set(beschrijving, forKey: "nieuwsBeschrijving")
UserDefaults.standard.set(image,forKey: "nieuwsPlaatje")
UserDefaults.standard.set(titel, forKey: "nieuwsTitel")
self.performSegue(withIdentifier: "gotonews", sender: nil)
}
}
And I don't know if you will need this to answer this question but I'll also post the "UsersII" (defined as users just above the viewDidLoad method) in case this is needed to answer the question.
import UIKit
class UsersII: NSObject {
var name: String?
var beschrijving: String?
var plaatje: String?
init(dictionary: [String: Any]) {
self.name = dictionary["title"] as? String ?? ""
self.beschrijving = dictionary["beschrijving"] as? String ?? ""
self.plaatje = dictionary["image"] as? String ?? ""
}
}
so what I want to achieve is that if you click on one of the cells, you get the parent id of the article, so in this case that would be the "-KWLSAIh5WJvNJOkxBEr or -KWLSTak0H20X_2Qnanv" I mentioned above in my firebase database structure.
Here is what i was saying you to do:
Your model class:
class UsersII: NSObject {
var parentId: String?
var name: String?
var beschrijving: String?
var plaatje: String?
init(dictionary: [String: Any],parentId:String) {
self.name = dictionary["title"] as? String ?? ""
self.beschrijving = dictionary["beschrijving"] as? String ?? ""
self.plaatje = dictionary["image"] as? String ?? ""
self.parentId = parentId
}
}
Fetch user method:
func fetchUser() {
Database.database().reference().child("Blog").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = UsersII(dictionary: dictionary,parentId:snapshot.key)
self.users.append(user)
print(snapshot)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)
}
And finaly you didSelect:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = users.reversed()[indexPath.row]
guard let beschrijving = message.beschrijving else {
return
}
guard let image = message.plaatje else {
return
}
guard let titel = message.name else {
return
}
guard let parentId = message.name else
{
return
}
UserDefaults.standard.set(beschrijving, forKey: "nieuwsBeschrijving")
UserDefaults.standard.set(image,forKey: "nieuwsPlaatje")
UserDefaults.standard.set(titel, forKey: "nieuwsTitel")
UserDefaults.standard.set(parentId,forKey: "nieuwsParentId")
self.performSegue(withIdentifier: "gotonews", sender: nil)
}
}

Array printing same results from API call

I am building an app whereby you enter ingredients and you return a bunch of recipes based on your input. I'm making the calls to the API using alamofire and these seem to be successful. The problem I'm having is the 6 results in my test call are repeating 1 recipe 6 times rather than returning all the results in separate cells. This is the API call code:
import Alamofire
class RecipeAp: NSObject{
var concoctions = [RecipeDetails]()
func provideRecipeDetailsForName(name: String, completed:#escaping ([RecipeDetails]) -> Void) {
let urlSearchString = URL_FULL + "onion" + "soup"
Alamofire.request(urlSearchString).responseJSON(completionHandler: { response in
let details = RecipeDetails()
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let matches = dict["matches"] as? [[String: Any]] {
for ingredient in matches {
if let name = ingredient["ingredients"] as? [String] {
details.ingredients = name
self.concoctions.append(details)
}
}
for recipeName in matches {
if let name = recipeName["recipeName"] as? String {
details.recipeTitle = name
print("the recipe name = \(name.debugDescription)")
self.concoctions.append(details)
}
}
}
completed(self.concoctions)
}
})
}
}
This is my model:
class RecipeDetails: NSObject {
var recipeID: String?
var recipeImageURL: String?
var recipeTitle: String?
var recipeSourceURL: String?
var recipePublisher: String?
var ingredients: [String]?
}
This is my customCell setup
import UIKit
class RecipeListCustomCell: UITableViewCell {
#IBOutlet weak var recipeTitle: UILabel!
#IBOutlet weak var recipeUrl: UILabel!
var recipe: RecipeDetails? {
didSet {
updateView()
}
}
func updateView() {
recipeTitle.text = recipe?.recipeTitle
recipeUrl.text = recipe?.recipeSourceURL
}
}
And finally this is my viewController
import UIKit
class MainVC: UIViewController {
#IBOutlet weak var tableView: UITableView!
var recipe = RecipeAp()
var results = [RecipeDetails]()
override func viewDidLoad() {
super.viewDidLoad()
loadRecipes()
}
func loadRecipes() {
recipe.provideRecipeDetailsForName(name: "onion" + "soup") { (response) in
self.results = response
self.tableView.reloadData()
}
}
}
extension MainVC: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"RecipeListCustomCell", for: indexPath) as! RecipeListCustomCell
let recipe = results[indexPath.row]
cell.recipe = recipe
return cell
}
}
Not sure how to display all the recipes separately in each cell. I have also attached some screen shots on what I am getting back from the API and the display in the simulator.
You create only one instance of RecipeDetails for each response. So, you add exactly the same reference into your self.concoctions repeatedly.
You may need to write something like this:
func provideRecipeDetailsForName(name: String, completed: #escaping ([RecipeDetails]) -> Void) {
let urlSearchString = URL_FULL + "onion" + "soup"
Alamofire.request(urlSearchString).responseJSON(completionHandler: { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let matches = dict["matches"] as? [[String: Any]] {
for match in matches {
//### Create a new instance for each iteration.
let details = RecipeDetails()
if let ingredients = match["ingredients"] as? [String] {
details.ingredients = ingredients
}
if let recipeName = match["recipeName"] as? String {
details.recipeTitle = recipeName
print("the recipe name = \(recipeName.debugDescription)")
}
//### Add the instance once in the iteration
self.concoctions.append(details)
}
}
completed(self.concoctions)
}
})
}

How do I create a drill down UITable in a single view using pre-populated data from API call?

I am trying to create a selection method for users to pick a football team using UITableView.
When the View Controller loads I make an API call and fetch and populated the following arrays in custom structs:
Country [name,id]
Divisions [id, country_id, name]
Teams [id, division_id, name]
The process is:
The user first selects a country > the ID of this country is then used to populate the table with all the divisions from that country > a division is selected which brings up all the teams in that division > a team is selected and the team name and id are passed to a variable to be used elsewhere.
At the moment the table displays all the countries. Once a user selects a country I am using print (self.newCountries[cellCountryId!]) to identifies and print the name of the country and it's id.
How do I now take that data and re-populate the table where Divisions.country_id = (self.newCountries[cellCountryId!])
This is my code:
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
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
cellCountryId = indexPath.row
print (self.newCountries[cellCountryId!])
}
override func viewDidLoad() {
super.viewDidLoad()
self.teamsTableView.delegate = self
self.teamsTableView.dataSource = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func backButtonTapped(_ sender: AnyObject) {
self.dismiss(animated: true) {
return
}
}
}

Resources