I m building iOS application using swift 4.2 and I have a TableViewController that have a strange behaviour.
This is the code:
import UIKit
class StoreByCategoryViewController: UITableViewController{
#IBOutlet var storeTableView: UITableView!
var categorySelected:CategoryModel?
var listaStore = [StoreModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Elenco Partner"
if((categorySelected) != nil && categorySelected?.id != "0"){
//posso chiamare il WS estraendo tutti i negozi
//per categoria
getStoreByCategory(category : self.categorySelected!);
storeTableView.reloadData()
}else{
getStore();
}
storeTableView.delegate = self
storeTableView.dataSource = self
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return listaStore.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return listaStore.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = storeTableView.dequeueReusableCell(withIdentifier:"customCell") as! StoreTableViewCell
let storeModel = listaStore[indexPath.row]
cell.storeAddress.text = storeModel.address
cell.storePhone.text = storeModel.phoneNumber
cell.storeDescription.text = storeModel.description
if(storeModel.imageUrl != ""){
print(storeModel.imageUrl)
let imageUrl:NSURL = NSURL(string: storeModel.imageUrl!)!
print(storeModel.imageUrl)
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: imageUrl as URL)!
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
cell.storeImage.image = image
cell.storeImage.contentMode = .scaleToFill
}
}
}
// cell.storeImage.layer.cornerRadius = cell.storeImage.frame.height / 2
return cell
}
func getStoreByCategory(category : CategoryModel){
var params = [
"cat_id" : category.id
]
let postUrl = APIRequest(endPoint: "get_store_by_category")
postUrl.sendRequest(parameters: params as! [String : String]) {
responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
do{
let messageData = try JSONDecoder().decode(ResponseStoreByCategoryModel.self, from: responseObject)
var array = messageData.result
for store in array {
var imageUrl = ""
if(store.image.count > 0){
imageUrl = store.image[0].image
}
let s = StoreModel(id: "",
description: store.firstName,
imageUrl: imageUrl,
address: store.address,
phoneNumber: store.phone)
self.listaStore.append(s)
}
self.storeTableView.reloadData()
}catch{
print("errore durante la decodifica dei dati")
}
}
}
func getStore(){
var params = [
"" : ""
]
let postUrl = APIRequest(endPoint: "get_store")
postUrl.sendRequest(parameters: params as! [String : String]) {
responseObject, error in
let user = CategoryModel(id: "0",
description: "Tutti",
imageUrl: "")
//self.listaCategorie.append(user)
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
do{
let messageData = try JSONDecoder().decode(ResponseStoreModel.self, from: responseObject)
var array = messageData.result
for store in array {
var imageUrl = ""
if(store.image.count > 0){
imageUrl = store.image[0].image
}
let s = StoreModel(id: "",
description: store.firstName,
imageUrl: imageUrl,
address: store.address,
phoneNumber: store.phone)
self.listaStore.append(s)
}
self.storeTableView.reloadData()
}catch{
print("errore durante la decodifica dei dati")
}
}
}
}
Method getStore, getStoreByCategory, return 9 items, but the method
numberOfSection and the method to populate customCell, are called 3 times. So i have a table with 27 items instead of 9 items.
Looks like you want only 1 section with 9 rows in it. If that's the case, you can return 1 from numberOfSections implementation.
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
The other thing I noticed is - you have a UITableViewController and an #IBOutlet var storeTableView: UITableView! as well. You don't need the outlet, You can use self.tableView for the same.
Related
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?
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)
}
}
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.
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
}
}
I'm new at swift closures.
I have this code and i can't extract the values from the forloop into the arrays outside the closure.
Sorry about this question but i have already searched stackflow but without success in this specific case.
Thanks in advance.
var namesArray: [String] = []
var imagesArray: [String] = []
var timesArray: [String] = []
var placesArray: [String] = []
func getData(){
//DATA SOURCE
// Create request for user's Facebook data
let request = FBSDKGraphRequest(graphPath: cmp.pageId, parameters: ["fields": "events"])
// Send request to Facebook
request.startWithCompletionHandler {
(connection, result, error) in
if error != nil {
// Some error checking here
print(error.debugDescription)
} else
if let pageData = result["events"] {
print(result["events"]!!["data"]!![0]["name"])
if let eventDetails = pageData!["data"] {
// EVENT DETAILS FETCH
for var i = 0; i < eventDetails!.count; i++
{
let fetchedEventName = eventDetails![i]["name"] as? String!
let fetchedEventTime = eventDetails![i]["start_time"] as? String!
if eventDetails?[i]["place"]??["name"] != nil {
if let fetchedEventPlace = eventDetails?[i]["place"]??["name"] {
self.placesArray.append(fetchedEventPlace! as! String)
}
} else {
self.placesArray.append("Lisbon")
}
self.namesArray.append(fetchedEventName!)
self.timesArray.append(fetchedEventTime!)
}
print("Name of event: \(self.namesArray)")
}
} else {
print("Error.")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
getData()
}
EDIT: I want to show the fetched result into a tableview that's already set.
Heres the tableview code.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("previewCell") as? PreviewCell {
var img: UIImage!
let url = NSURL(string: imagesArray[indexPath.row])!
if let data = NSData(contentsOfURL: url){
img = UIImage(data: data)
} else {
img = UIImage(named: "ant")
}
cell.configureCell(img, title: namesArray[indexPath.row], time: timesArray[indexPath.row], place: placesArray[indexPath.row])
return cell
} else {
return PreviewCell()
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesArray.count
}
func addNewEvent(name: String, image: String, time: String, place: String)
{
namesArray.append(name)
imagesArray.append(image)
timesArray.append(time)
placesArray.append(place)
}
You are already getting the number in to the arrays so what you need to do is just reload the tableview after the for loop.
//end of for-loop
self.tableView.reloadData()
The reason for this is the asynchronous execution of the request.startWithCompletionHandler. The code inside that block will most likely execute after your tableView already loaded and it therefor needs a reload after the data has been fetched
In case if you need to return data from closure you can define completion on your getData() method like this
func getData(completion:([DataType]) -> Void) {
//process data
let dataArray:DataType = []
completion(dataArray)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
getData { (completionData) -> Void in
// process returned data
}
}
Hope this helps