I have a list of data coming in from json. With this list I would like to load it into a tableview but within two seperate sections called Featured and All. Trying to figure out how to get my "Featured" section not to load the same amount of rows as the "All" section. All section is good but Featured section shows Featured list plus 16 empty rows. Any ideas on how I get rid of these extra rows in the Featured section?
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(section == 0)
{
return "Featured"
}
return "All"
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var sections: Int = 2
return sections
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count: Int = tableData.count
println("tabledata \(count)")
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let session = NSURLSession.sharedSession()
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let entry : NSMutableDictionary = self.tableData[indexPath.row] as! NSMutableDictionary
var featured = entry["Business_IsFeatured"] as? String
if ((featured == "1") && (indexPath.section == 0))
{
var busName = entry["Business_Name"] as? String
var points = entry["Member_Points"] as? String
var imageName = entry["Business_Image"] as? String
var imgURL: NSURL = NSURL(string: "http://www.example.com/images/\(imageName!)")!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
cell.textLabel!.text = busName
cell.textLabel!.numberOfLines = 0
cell.detailTextLabel!.text = "Points: \(points!)"
cell.imageView!.image = UIImage(data: data)
}
})
}
else
{
if((featured == "0") && (indexPath.section == 1))
{
var busName = entry["Business_Name"] as? String
var points = entry["Member_Points"] as? String
var imageName = entry["Business_Image"] as? String
var imgURL = NSURL(string: "http://www.example.com/images/\(imageName!)")
cell.textLabel!.text = busName
cell.textLabel!.numberOfLines = 0
cell.detailTextLabel!.text = "Points: \(points!)"
cell.imageView!.hnk_setImageFromURL(imgURL!, format: Format<UIImage>(name: "original"))
}
}
return cell
}
Your implementation of UITableViewDataSource's
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
method needs to supply the number of rows you intend for each section to contain. Your code returns the same number of rows regardless of the section, which sounds wrong based on how you describe what you want to do. You need to calculate and return the number of featured items for your Featured section, rather than the size of your entire dataset.
The "tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int" function is here for this. Depending of the section, you return the numbers of rows into this section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(section==0){
var count: Int = tableData.count
println("tabledata \(count)")
return count
}else{
return theOtherData.count
}
}
#tomsoft and #ScorpioCurse I was able to get the featured section to load up the correct data by making two seperate arrays for the data. Before I was trying to return count which swift wasnt liking. After changing it to return a separate array tableFeatData.count else return tableData.count I got it working. I also had to add a second dictionary. Code below. I may still need to clean up some of this code.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let session = NSURLSession.sharedSession()
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let entry : NSMutableDictionary = self.tableData[indexPath.row] as! NSMutableDictionary
var featured = entry["Business_IsFeatured"] as? String
if ((featured != "1") && (indexPath.section == 0))
{
let featentry: NSMutableDictionary = self.tableFeatData[indexPath.row] as! NSMutableDictionary
var busName = featentry["Business_Name"] as? String
var points = featentry["Member_Points"] as? String
var imageName = featentry["Business_Image"] as? String
var imgURL: NSURL = NSURL(string: "http://www.example.com/images/\(imageName!)")!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
cell.textLabel!.text = busName
cell.textLabel!.numberOfLines = 0
cell.detailTextLabel!.text = "Points: \(points!)"
cell.imageView!.image = UIImage(data: data)
}
})
}
else
{
var busName = entry["Business_Name"] as? String
var points = entry["Member_Points"] as? String
var imageName = entry["Business_Image"] as? String
var imgURL = NSURL(string: "http://www.example.com/images/\(imageName!)")
cell.textLabel!.text = busName
cell.textLabel!.numberOfLines = 0
cell.detailTextLabel!.text = "Points: \(points!)"
cell.imageView!.hnk_setImageFromURL(imgURL!, format: Format<UIImage>(name: "original"))
}
return cell
}
Related
I'm working on displaying data from a plist in multiple "drill down" tableViews. The displayed data is only going to be read-only and I don't want it to necessarily be based on web data, and there will only be a maximum of about 100 data points so I'm fairly happy with plist instead of JSON.
Anyway, the question... I've got an array of dictionary items that I'm managing to display fairly well. I started with the GitHub relating to the following question on stack overflow (I modified it a little bit but thats not important).
Load data from a plist to two TableViews
https://github.com/DonMag/SWPListData
What I need help with is displaying an array of items ("friends" in this example) under each person. Code below will hopefully explain.
I've created an empty array in the model
struct EmployeeDetails {
let functionary: String
let imageFace: String
let phone: String
//This is the new array I've added and am having trouble displaying
let friends: [String]
init(dictionary: [String: Any]) {
self.functionary = (dictionary["Functionary"] as? String) ?? ""
self.imageFace = (dictionary["ImageFace"] as? String) ?? ""
self.phone = (dictionary["Phone"] as? String) ?? ""
//I've initialised it here.
self.friends = (dictionary["Friends"] as? [String]) ?? [""]
Now in the viewController displaying the data. I don't have any problems at all displaying the correct data for the "functionary", "imageFace" and "phone" - but I just can't seem to display "friends" as an array in its own section. I'm pretty sure the main problem is in numberOfRows and cellForRow:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if let theEmployee = newPage {
return theEmployee.details.count
}
return 0
}
else if section == 1 {
return 1
}
else if section == 2 {
if let theEmployee = newPage {
return theEmployee.details.count
}
return 0
}
else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // as! TableViewCell2
if indexPath.section == 0 {
cell.textLabel?.text = "A"
if let theEmployee = newPage {
cell.textLabel?.text = theEmployee.details[indexPath.row].functionary
cell.detailTextLabel?.text = theEmployee.details[indexPath.row].phone + " (" + theEmployee.details[indexPath.row].imageFace + ")"
}
}
else if indexPath.section == 1 {
cell.textLabel?.text = "Test"
}
else if indexPath.section == 2 {
cell.textLabel?.text = ????
}
return cell
}
I thought it would work writing the following in numberOfRows:
else if section == 2 {
if let theEmployee = newPage {
return theEmployee.details.friends.count
}
return 0
}
But I get the error:
value of type '[EmployeeDetails]' has no member 'friends'.
What do I need to do to get that array?
Note: The array is not empty.
Any suggestions/help would be much appreciated!
Problem is that you are accessing the friends property on details whereas it is a property on the structs stored inside details so you would have to access it through indexing something like this
theEmployee.details[yourIndex].friends.count
Update:
//First you need to make changes inside the .plist file, please go there and add Friends Array inside just like Details
Now this will require you to change your Employee struct code
struct Employee {
let position: String
let name: String
let details: [EmployeeDetails]
let friends: [String]
init(dictionary: [String: Any]) {
self.position = (dictionary["Position"] as? String) ?? ""
self.name = (dictionary["Name"] as? String) ?? ""
let t = (dictionary["Details"] as? [Any]) ?? []
self.details = t.map({EmployeeDetails(dictionary: $0 as! [String : Any])})
self.friends = (dictionary["Friends"] as? [String]) ?? []
}
}
Next step would be to add this in the table view as follows
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let theEmployee = newPage {
if section == 0 {
return theEmployee.details.count
}else if section == 1 {
return theEmployee.friends.count
}
}
return 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Subordinates"
}else if section == 1 {
return "Friends"
}
return ""
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // as! TableViewCell2
cell.textLabel?.text = "A"
if let theEmployee = newPage {
if indexPath.section == 0 {
cell.textLabel?.text = theEmployee.details[indexPath.row].functionary
cell.detailTextLabel?.text = theEmployee.details[indexPath.row].phone + " (" + theEmployee.details[indexPath.row].imageFace + ")"
}else if indexPath.section == 1 {
cell.textLabel?.text = theEmployee.friends[indexPath.row]
}
}
return cell
}
}
when i keep break points at the point mentioned in image then the data was loading without crashing the application and when i didn't kept the break points and make the application to run then it was crashing can any one help me how to clear the error
my code is shown below
let url = "http://www.json-generator.com/api/json/get/bUKEESvnvS?indent=2"
var orderdetailsArray : [[String:AnyObject]] = []
var itemsArray : [[String:AnyObject]] = []
var orderid = [Any]()
var orderdate = [Any]()
var subTotal = [Int]()
var shippingPrice = [Int]()
var tax = [Int]()
var grandTotal = [Int]()
var shippingAddress = [AnyObject]()
var shippingMethod = [AnyObject]()
var billingAddress = [AnyObject]()
var paymentMethod = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
tableDetails.delegate = self
tableDetails.dataSource = self
tableDetails.estimatedRowHeight = 600
// Do any additional setup after loading the view.
}
func downloadJsonWithURL() {
let url = NSURL(string: self.url)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
self.orderdetailsArray = (jsonObj!.value(forKey: "Orders detail") as? [[String: AnyObject]])!
if let firstDictInfo = self.orderdetailsArray.first as? [String:Any] {
self.itemsArray = firstDictInfo["Items detail"] as! [[String : AnyObject]]
}
OperationQueue.main.addOperation({
self.tableDetails.reloadData()
})
}
}).resume()
}
func numberOfSections(in tableView: UITableView) -> Int{
return 3
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (section == 0){
return ""
}
else if (section == 1){
return ""
}
else{
return "Ordered Items"
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.darkGray
header.textLabel?.textAlignment = NSTextAlignment.center
header.textLabel?.font = UIFont(name: "Futura", size: 17)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0){
return 1
}else if (section == 1){
return 1
}
else{
return itemsArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (indexPath.section == 0)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ordercell", for: indexPath) as! OrdersTableViewCell
cell.orderDateLabel.text = orderdetailsArray[0]["OrderDate"] as? String
cell.orderIdLabel.text = orderdetailsArray[0]["OrderId"]! as? String
let totalPrice : Int = orderdetailsArray[0]["Shipping"]! as! Int
let price = Float(totalPrice)
cell.shippingLabel.text = "$" + "\(price)"
let subTotalPrice : Int = orderdetailsArray[0]["SubTotal"]! as! Int
let subtotalprice = Float(subTotalPrice)
cell.subTotalLabel.text = "$" + "\(subtotalprice)"
let taxPrice : Int = orderdetailsArray[0]["Tax"]! as! Int
let taxPriceFloat = Float(taxPrice)
cell.taxLabel.text = "$" + "\(taxPriceFloat)"
let grandTotal : Int = self.orderdetailsArray[0]["GrandTotal"]! as! Int
let grandPriceFloat = Float(grandTotal)
cell.grandTotalLabel.text = "$" + "\(grandPriceFloat)"
return cell
}
else if (indexPath.section == 1){
let cell = tableView.dequeueReusableCell(withIdentifier: "shippingcell", for: indexPath) as! ShippingTableViewCell
cell.shippingMethodLabel.text = orderdetailsArray[0]["ShippingMethod"] as? String
cell.shippingAddressLabel.text = orderdetailsArray[0]["ShippingAddress"]! as? String
cell.billingAddressLabel.text = orderdetailsArray[0]["BillingAddress"]! as? String
cell.paymentMethodLabel.text = orderdetailsArray[0]["PayMentMethod"]! as? String
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "orderdetailscell", for: indexPath) as! OrderDetailsTableViewCell
let array = itemsArray[indexPath.row]
let price : Int = array["ItemPrice"] as! Int
let grandPriceFloat = Float(price)
cell.priceLabel.text = "$" + "\(grandPriceFloat)"
let quant : Int = array["ItemQty"] as! Int
cell.quantityLabel.text = "\(quant)"
cell.productNameLabel.text = array["ItemName"] as? String
let subTotal : Int = array["ItemSubTotal"] as! Int
let subPriceFloat = Float(subTotal)
cell.subTotalLabel.text = "$" + "\(subPriceFloat)"
let grandTotal : Int = array["ItemSku"] as! Int
cell.skuLabel.text = "\(grandTotal)"
return cell
}
}
You need to confirm if orderDetailsArray actually contains some value before you are accessing it. Also, you are just returning 1 for numberOfRowsInSection without even checking if orderDetailsArray has some content. This should possibly resolve your crash:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if (section == 0 || section == 1) {
if orderDetailsArray.count > 0 {
return 1
} else {
return 0
}
}
else {
return itemsArray.count
}
}
I am not sure if this is the kind of behavior you are expecting because it will result in section Headers with no rows but, you can modify that!
Need to register UINib in UITableView for use multiple custom cell in tableView.
How to register UINib in UITableView?
Just write below three line in ViewDidLoad()
tableView.register(UINib(nibName: "ShippingTableViewCell", bundle: nil), forCellReuseIdentifier: "shippingcell")
tableView.register(UINib(nibName: "OrderDetailsTableViewCell", bundle: nil), forCellReuseIdentifier: "orderdetailscell")
tableView.register(UINib(nibName: "OrdersTableViewCell", bundle: nil), forCellReuseIdentifier: "ordercell")
App crashes and shows the following error:
Invalid update: invalid number of sections. The number of sections
contained in the table view after the update (6) must be equal to the
number of sections contained in the table view before the update (3),
plus or minus the number of sections inserted or deleted (0 inserted,
0 deleted).' Please Help
My code:
func numberOfSections(in tableView: UITableView) -> Int {
return newsArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath) as? NewsTableViewCell
cell?.contentView.backgroundColor = UIColor.clear
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 4, width: self.view.frame.size.width - 20, height: 410))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
whiteRoundedView.layer.shadowOpacity = 0.2
cell?.contentView.addSubview(whiteRoundedView)
cell?.contentView.sendSubview(toBack: whiteRoundedView)
let newsdata = newsArray[indexPath.section]
let date = NSDate(timeIntervalSince1970: TimeInterval(newsdata.meta))
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY "
let dateString = dayTimePeriodFormatter.string(from: date as Date)
print(dateString)
if let newsImg = self.newsImageCache.object(forKey: indexPath.section as AnyObject){
cell?.imageOut.image = newsImg as? UIImage
} else {
loadImageFromWeb(uri: newsdata.photo, cache: self.newsImageCache, indexpath: indexPath)
}
cell?.titleLabel.text = newsdata.title
cell?.descLabel.text = newsdata.body
return cell!
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.section + 3 == self.newsArray.count {
loadDatafromUrl()
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
// Make the background color show through
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.backgroundColor = UIColor.clear
return headerView
}
func loadDatafromUrl(){
let uri = "http://localhost/unani-info/admin/json/news.php"
print(uri)
if let url = URL(string: uri){
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let session = URLSession(configuration: config)
let task = session.dataTask(with: url, completionHandler: {
(rawData,response,error) in
if error != nil {
print("Couldnt load data")
print(error?.localizedDescription as Any)
} else {
if let data = rawData {
do{
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [AnyObject]{
for index in 0...json.count-1 {
if let datas = json[index] as? [String: AnyObject] {
let newsObj = News()
newsObj.title = datas["title"] as! String
newsObj.body = datas["body"] as! String
let photo = datas["photo"] as! String
let photourl = "http://localhost/unani-info/admin/uploads/" + photo
newsObj.photo = photourl
newsObj.meta = datas["meta"] as! Int
self.newsArray.append(newsObj)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}catch{
print("error")
}
}
}
})
task.resume()
}
}
Can you please try:
DispatchQueue.main.async {
for index in 0...json.count-1 {
if let datas = json[index] as? [String: AnyObject] {
let newsObj = News()
newsObj.title = datas["title"] as! String
newsObj.body = datas["body"] as! String
let photo = datas["photo"] as! String
let photourl = "http://localhost/unani-info/admin/uploads/" + photo
newsObj.photo = photourl
newsObj.meta = datas["meta"] as! Int
self.newsArray.append(newsObj)
}
}
self.tableView.reloadData()
}
Instead of:
for index in 0...json.count-1 {
if let datas = json[index] as? [String: AnyObject] {
let newsObj = News()
newsObj.title = datas["title"] as! String
newsObj.body = datas["body"] as! String
let photo = datas["photo"] as! String
let photourl = "http://localhost/unani-info/admin/uploads/" + photo
newsObj.photo = photourl
newsObj.meta = datas["meta"] as! Int
self.newsArray.append(newsObj)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
You are inverting the numberOfSections and numberOfRowsInSection. You should have:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return newsArray.count
}
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 have UITableViewController with files from document folder. I name the cells by artist name. I have three artist and four songs. UITableViewCell shows two cells with the same artist. How can I fix it?
This code export data from document folder
var mp3Files: Array<String!>!
func exportData() {
var generalURL: [AnyObject]?
var arrayFiles: Array<NSURL!>!
var directory = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var urlFromDirectory = directory.first as! NSURL
var file = fileManager.contentsOfDirectoryAtURL(urlFromDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil)!
println("file \(file)")
mp3Files = file.map(){ $0.lastPathComponent }.filter(){ $0.pathExtension == "mp3" }
println("mp3 files \(mp3Files)")
}
and code fill the UITableViewCell
var cellStrings: String!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
var dataForCell = mp3Files[indexPath.row]
var generalURL: NSURL!
var documentFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
if var urlFromFolder: NSURL = documentFolder.first as? NSURL {
generalURL = urlFromFolder.URLByAppendingPathComponent(dataForCell)
println("general \(generalURL)")
}
var player = AVPlayerItem(URL: generalURL)
var metaData = player.asset.commonMetadata as! [AVMetadataItem]
for item in metaData {
if item.commonKey == "artist" {
nameArtist = item.stringValue
}
}
cell.textLabel?.text = nameArtist
//
cellStrings = cell.textLabel?.text
println("cell strings \(cellStrings)")
// Configure the cell...
return cell
}
var superArray = [String]()
var filterArray = [String]()
func filter() {
var proString: String!
for proItem in mp3Files {
var proFolder = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
var americaURL: NSURL!
if var proURL: NSURL = proFolder.first as? NSURL {
americaURL = proURL.URLByAppendingPathComponent(proItem)
}
var proPlayerItem = AVPlayerItem(URL: americaURL)
var proData = proPlayerItem.asset.commonMetadata as! [AVMetadataItem]
for proFiles in proData {
if proFiles.commonKey == "artist" {
superArray.append(proFiles.stringValue)
}
}
}
filterArray = Array(Set(superArray))
filterArray.sort(){ $0 < $1 }
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1 ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return filterArray.count ?? 0
}
var name: String!
var nameArtist: String!
//
var cellStrings: String!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
nameArtist = filterArray[indexPath.row]
cell.textLabel?.text = nameArtist
return cell
}