Multiple layer added in tableview - ios

I am trying to set data on tableview dynamically and cell can be deleted by swiping.cell create multiple layer and after deletion some layer is exist,its appear cell has not deleted.
my code is here ..
override func viewDidLoad() {
super.viewDidLoad()
self.beaconArrayM = NSMutableArray()
self.produsctListM = NSMutableArray()
self.contentArrayM = NSMutableArray()
self.fatchDataFromApiAsync(urlString: videoUrl)//video url
countBeacons = 0
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
}
func fatchDataFromApiAsync(urlString:String) {
_ = NSArray()
let url:URL = URL(string: urlString)!
URLSession.shared.dataTask(with: url){ data,response,error in
if error != nil {
print("Data Parsing error = \(error)")
}
else{
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:AnyObject]
if jsonResponse["assets"] != nil{
self.jsonArray = jsonResponse["assets"] as! NSArray
self.HeaderStr = jsonResponse["identifier"] as? String
self.navigationController?.navigationBar.topItem?.title = self.HeaderStr
self.beaconManager.delegate = self
self.swipeTableview.delegate = self
self.swipeTableview.dataSource = self
}
}
catch let error as NSError{
print("\(error)")
}
}
}.resume()
}
}
extension DemoListBeaconsVC: ESTBeaconManagerDelegate
{
// :MARK BeaconsManager ranging delegates
func beaconManager(_ manager: Any, didEnter region: CLBeaconRegion) {
countBeacons += 1
if !(region.minor == nil){
let minorValue = region.minor
if !(self.beaconArrayM.contains(minorValue!)){
self.beaconArrayM .add(minorValue!)
}
self.contentArrayM = self.beaconArrayM
self.swipeTableview.reloadData()
}
}
func downloadImage(url: URL,indexPath: IndexPath,productTxt : String) {
let cell = self.swipeTableview.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell
print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() { () -> Void in
cell.productImage.contentMode = .scaleAspectFit
cell.productImage.image = UIImage(data: data)
cell.contentLbl.text = productTxt
}
}
}
func getDataFromUrl(url: URL, completion: #escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func beaconManager(_ manager: Any, didExitRegion region: CLBeaconRegion) {
countBeacons -= 1
// if countBeacons == 0{
// }
if (((self.beaconArrayM.count)) > 0 && !(region.minor == nil)){
self.beaconArrayM.remove(region.minor!)
self.contentArrayM = self.beaconArrayM
self.swipeTableview.reloadData()
}
}
func beaconManager(_ manager: Any, didDetermineState state: CLRegionState, for region: CLBeaconRegion) {
switch state {
case CLRegionState.inside:
if region == beaconRegion
{
self.beaconManager.startMonitoring(for: beaconRegion)
}
else if region == beaconRegion
{
self.beaconManager.startMonitoring(for: beaconRegion2)
}
else if region == beaconRegion
{
self.beaconManager.startMonitoring(for: beaconRegion3)
}
print("inside REGION",region.description)
break
case CLRegionState.outside:
// Stop Monitoring
if region == beaconRegion
{
self.beaconManager.stopMonitoring(for: beaconRegion)
}
else if region == beaconRegion
{
self.beaconManager.stopMonitoring(for: beaconRegion2)
}
else if region == beaconRegion
{
self.beaconManager.stopMonitoring(for: beaconRegion3)
}
print("outside REGION",region.description)
break
case CLRegionState.unknown:
print("unknown REGION",region.description)
break
}
}
func beaconManager(_ manager: Any, didChange status: CLAuthorizationStatus) {
switch status {
case .authorizedAlways:
self.beaconManager.requestAlwaysAuthorization()
print("authorizedAlways")
break
default:
print("defaultt")
break
}
}
func beaconManager(_ manager: Any, rangingBeaconsDidFailFor region: CLBeaconRegion?, withError error: Error) {
}
func beaconManager(_ manager: Any, didFailWithError error: Error) {
}
func beaconManager(_ manager: Any, didStartMonitoringFor region: CLBeaconRegion) {
if region == beaconRegion
{
self.beaconManager.requestState(for: beaconRegion)
}
else if region == beaconRegion
{
self.beaconManager.requestState(for: beaconRegion2)
}
else if region == beaconRegion
{
self.beaconManager.requestState(for: beaconRegion3)
}
}
func beaconManager(_ manager: Any, monitoringDidFailFor region: CLBeaconRegion?, withError error: Error) {
}
}
//: MARK Tableview delegate and datasource
extension DemoListBeaconsVC : UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "Cell"
// print("Begin cellForRowAt")
let cell = self.swipeTableview.dequeueReusableCell(withIdentifier: identifier) as! SwipeTableViewCell
if (self.contentArrayM.count) > 0 {
var currentIndex: Int = 0
let countIndex: Int = 0
for tempp in self.contentArrayM{
let temp = jsonArray .object(at: indexPath.row)
self.jsonDic = temp as! NSDictionary
self.minor = self.jsonDic["minor"] as? String
if let minorInteger = Int(self.minor!) {
minorNumber = NSNumber(value:minorInteger)
}
if minorNumber == tempp as! NSNumber
{
currentIndex = countIndex
break
}
}
// let temp = jsonArray .object(at: currentIndex)
let temp = jsonArray .object(at: indexPath.row)
self.jsonDic = temp as! NSDictionary
self.minor = self.jsonDic["minor"] as? String
self.HeaderStr = self.jsonDic["title"] as? String
self.urlStr = self.jsonDic["url"] as? String
print("minor",self.minor!)
if let minorInteger = Int(self.minor!) {
minorNumber = NSNumber(value:minorInteger)
}
}
let url = NSURL(string: self.urlStr!)
downloadImage(url: url as! URL, indexPath: indexPath, productTxt: self.HeaderStr!)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100.0
}
func actionGesture(recognizer: UITapGestureRecognizer)
{
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let temp = jsonArray .object(at: indexPath.row)
self.jsonDic = temp as! NSDictionary
self.HeaderStr = self.jsonDic["title"] as? String
self.urlStr = self.jsonDic["url"] as? String
let demoVC = self.storyboard?.instantiateViewController(withIdentifier: "ProductDetalsVC") as! ProductDetalsVC
demoVC.productTitle = self.HeaderStr
demoVC.imageStr = self.urlStr
self.navigationController?.pushViewController(demoVC, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .normal, title: "Delete")
{ action, index in
// print("delete")
self.swipeTableview.beginUpdates()
self.contentArrayM.removeObject(at: indexPath.row)
self.swipeTableview.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
print("array count after deletion",self.contentArrayM.count)
// self.swipeTableview.reloadRows(at: [indexPath], with: UITableViewRowAnimation.fade)
self.swipeTableview.endUpdates()
}
let done = UITableViewRowAction(style: .default, title: "Done")
{ action, index in
print("done")
}
return [delete, done]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// the cells you would like the actions to appear needs to be editable
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
print("Deleted")
self.contentArrayM.remove(at: indexPath.row)
self.swipeTableview.deleteRows(at: [indexPath], with: .automatic)
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.contentArrayM.count == 0
{
return 0
}
else
{
return self.contentArrayM.count
}
}
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
}

I have found the answer finally.
I was created tableview cell two time , First in cellForRowAtIndexPath and Second in function downloadImage().
Now i am sending cell into function downloadImage() as follow.
downloadImage(cell: cell, url: url!, indexPath: indexPath, productTxt: self.headerStr!)

Related

Trying to Populate a tableview with JSON Data. Getting tableview = UITableView? nil none

I am getting
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
at DispatchQueue.main.async{ self.tableView.reloadData() }
My code
import UIKit
class BrowseRequestsViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
final let url = URL(string: "")
private var browseRequestDataModel = [Datum]()
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
downloadJson()
}
func downloadJson() {
guard let downloadURL = url else { return }
URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
guard let data = data, error == nil, urlResponse != nil else {
print("something is wrong")
return
}
print("downloaded")
do {
let decoder = JSONDecoder()
let downloadedBrowseRequestData = try decoder.decode(BrowseRequestsDataModel.self, from: data)
self.browseRequestDataModel = downloadedBrowseRequestData.data
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch {
print("something wrong after downloaded")
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return browseRequestDataModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowseRequestsTableViewCell" ) as? BrowseRequestsTableViewCell else { return UITableViewCell() }
cell.shipperName.text = browseRequestDataModel[indexPath.row].user.name
cell.pickupLocation.text = browseRequestDataModel[indexPath.row].pickupLocation.pickupLocationCity + " , " + browseRequestDataModel[indexPath.row].pickupLocation.pickupLocationCountry
cell.dropoffLocation.text = browseRequestDataModel[indexPath.row].dropoffLocation.dropoffLocationCity + " , " + browseRequestDataModel[indexPath.row].dropoffLocation.dropoffLocationCountry
cell.item.text = browseRequestDataModel[indexPath.row].item.name
cell.pickupDate.text = browseRequestDataModel[indexPath.row].pickupDate
cell.dropoffDate.text = browseRequestDataModel[indexPath.row].dropoffDate
return cell
}
}

Value of type 'UITableViewCell' has no member 'name' in multiple TableView

I tried to make ViewController with two TableView but meet the problem.
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableTN: UITableView!
#IBOutlet weak var tableMainNews: UITableView!
var topnews: [TopNews]? = []
var mainnews: [Mainnewsfeed]? = []
override func viewDidLoad() {
super.viewDidLoad()
TopNewsJSON()
MainNewsJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell?
if tableView == self.tableTN {
cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell!.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell!.titleTN!.text = self.topnews?[indexPath.item].headline
}
if tableView == self.tableMainNews {
cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell!.mainnews_title!.text = self.mainnews?[indexPath.item].headline
}
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count:Int?
if tableView == self.tableTN {
count = self.topnews!.count
}
if tableView == self.tableMainNews {
count = self.mainnews!.count
}
return count!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print(indexPath)
}
func TopNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "https://sportarena.com/wp-api/topnews2018/top/")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
self.topnews = [TopNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
//print(json)
let TN = TopNews()
let jarray = json["top-news"] as! NSArray
let jarray1 = jarray[0] as? [String: AnyObject]
if let ID = jarray1!["ID"] as? String,
let title = jarray1!["title"] as? String,
let img = jarray1!["img"] as? String {
TN.headline = title
TN.image = img
TN.id = ID
}
self.topnews?.append(TN)
DispatchQueue.main.async {
self.tableTN.reloadData()
}
} catch let error {
print(error)
}
}
task.resume()
}
func MainNewsJSON () {
let urlRequest = URLRequest(url: URL(string: "anyurl")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error as Any)
return
}
//self.mainnews = [MainNews]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
let jarray = json["general-news"] as! NSArray
let jarray1 = jarray[0]
for jarray1 in jarray1 as! [[String: Any]] {
let MNF = Mainnewsfeed()
if let ID = jarray1["id"],
let title = jarray1["title"],
let time = jarray1["datetime"] {
MNF.headline = title as? String
MNF.id = ID as? String
MNF.time = time as? String
}
self.mainnews?.append(MNF)
DispatchQueue.main.async {
self.tableMainNews.reloadData()
}
}
} catch let error {
print(error)
}
}
task.resume()
}
}
}
After three lines as cell!.titleTN!.text = self.topnews?[indexPath.item].headline and others display error: "Value of type 'UITableViewCell' has no member 'titleTN'" (or also 'imgTN' and 'mainnews_title')
Where the error? What I need to change in my code?
Please help me.
You can try
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == self.tableTN {
let cell = tableView.dequeueReusableCell(withIdentifier: "topnewsCell", for:indexPath) as! TopNewsCell
cell.imgTN!.downloadImage(from: (self.topnews?[indexPath.item].image!)!)
cell.titleTN!.text = self.topnews?[indexPath.item].headline
return cell
}
else
{
let cell = tableView.dequeueReusableCell(withIdentifier: "mainnewsCell", for:indexPath) as! MainNewsCell
cell.mainnews_title!.text = self.mainnews?[indexPath.item].headline
return cell
}
}

Pull to Refresh on tableView

I want to pull to refresh for my RSS feed news app. I using navigation controller and table view controller. How should I do on Table View Controller? What should we add? My code is here.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}
1) Declare an property of type UIRefreshControl as:
var refreshControl = UIRefreshControl()
2) In viewDidLoad()method add this refreshControl to your table view as:
self.refreshControl.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
if #available(iOS 10, *){
self.tableView.refreshControl = self.refreshControl
}else{
self.tableView.addSubview(self.refreshControl)
}
Declare a property refreshControl in your TableViewController as
var refreshControl:UIRefreshControl?
The in viewDidLoad() function add the following code
refreshControl?.addTarget(self, action: #selector(loadRSS), for: .valueChanged)
self.tableView.addSubview(refreshControl!)
Update your loadRSS() function as
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
self.refreshControl?.endRefreshing(
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
Please refer following code , as i have added pull to refresh control on your code.
class TableviewController: UITableViewController {
var items : Array<Item> = []
var entries : Array<Entry> = []
var pullToFrefreshNews:UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
loadRSS()
loadAtom()
self.addPulltoRefrehs()
}
func addPulltoRefrehs() {
self.pullToFrefreshNews = UIRefreshControl()
self.pullToFrefreshNews.addTarget(self, action: #selector(TableviewController.loadRSS), for: UIControlEvents.valueChanged)
self.newsTableVU.addSubview(pullToFrefreshNews)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item:Item = self.items[indexPath.row]
cell.textLabel?.text = item.title
cell.detailTextLabel?.text = self.pubDateStringFromDate(item.pubDate! as Date)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = self.items[indexPath.row]
let url:URL = URL(string: item.link!)!
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true, completion: nil)
}
func loadRSS() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseRSS(xmlData: data as NSData, completionHandler: {(isSuccess, channel, error) -> Void in
if (isSuccess) {
self.items = channel!.items!
self.tableView.reloadData()
}
if (response.error != nil) {
print((response.error?.localizedDescription)! as String)
}
})
}
}
}
func loadAtom() {
let feedUrlString:String = "websiteurl"
Alamofire.request(feedUrlString).response { response in
if let data = response.data, let _ = String(data: data, encoding: .utf8) {
TIFeedParser.parseAtom(xmlData: data as NSData, completionHandler: {(isSuccess, feed, error) -> Void in
if (isSuccess) {
self.entries = feed!.entries!
self.tableView.reloadData()
}
if (error != nil) {
print((error?.localizedDescription)! as String)
}
})
}
}
}
func pubDateStringFromDate(_ pubDate:Date)->String {
let format = DateFormatter()
format.dateFormat = "yyyy/M/d HH:mm"
let pubDateString = format.string(from: pubDate)
return pubDateString
}
}

Group JSON data in Tableview with Swift

I'm creating an app for iOS that get data from my server with json and store it on a tableview; with this no problems, my data are simple notes, some notes are linked together forming projects (simple dependency_id on my database sql), my question is: How can i group my notes by project, like a contact list? (ex. http://img.wonderhowto.com/img/13/66/63535060544981/0/siri-exploit-you-could-bypass-iphones-lock-screen-call-message-any-contact-ios-7-1-1.w654.jpg)
This is the source that populate the table with all notes:
//
// TableController.swift
// uitableview_load_data_from_json
import UIKit
class TableController: UITableViewController {
var TableData:Array< String > = Array < String >()
var userid = NSUserDefaults.standardUserDefaults().stringForKey("userid")!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http:/localhost/index.php/iOS_getNomenTasks?n=" + userid)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(url:String)
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let json = NSString(data: data, encoding: NSASCIIStringEncoding)
self.extract_json(json!)
}else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
func extract_json(data:NSString)
{
var parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError)
if (parseError == nil)
{
if let task_list = json as? NSArray
{
for (var i = 0; i < task_list.count ; i++ )
{
if let tasj_obj = task_list[i] as? NSDictionary
{
if let task_id = tasj_obj["id"] as? String
{
if let task_name = tasj_obj["tk_title"] as? String
{
if let task_type = tasj_obj["tk_type"] as? String
{
TableData.append(task_name)
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
}
ok..
task_id is the note id,
task_name is the note name,
task_type is the value that identify if note is a project or not, if task_type is 0, the note is a simple note, if task_type is 1 the note is a project.
If you create an UITableViewController, you have the function :
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
With it, you have 3 sections who contains 2 lines :
var tab: [String] = ["section 1", "section 2", "section 3"]
var tabData: [AnyObject] = [["item1", "item2"],["item1", "item2"],["item1", "item2"]]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tab.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataTab[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = UITableViewCell()
return cell
}

table view not loading with swift

I have trouble in loading the table view when parsing json files in swift.
Parsing the data is doing well. But no data are displayed in the table view.
This is the code :
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var redditListTableView: UITableView!
var tableData = []
#IBAction func cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(false, completion: nil)
println("cancel")
}
#IBAction func done(sender: AnyObject) {
println("done")
}
override func viewDidLoad() {
super.viewDidLoad()
searchJsonFile("blabla.json")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(tableData.count)
return tableData.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
let rowData: NSString = self.tableData[indexPath.row] as NSString
cell.textLabel.text = rowData as String
return cell
}
func searchJsonFile(searchFile: String) {
let urlPath = "http://data.../\(searchFile)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
var results = [String]()
if let results1 = jsonResult["data"] as? NSDictionary{
for (key, value) in results1 {
if let eng = value["eng"] as? NSDictionary {
if let name = eng["name"] as? NSString{
results.append(name)
}
}
}
}
//println(results) OK!!!!
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.redditListTableView.reloadData()
})
})
task.resume()
}
}
You are returning 0 from numberOfSectionsInTableView - so you get no data displayed. You want 1 section -
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
If you are not having sections then just remove this function or comment
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
or else return 1

Resources