I am new to Swift , I am parsing my JSON by using ObjectMapper but I want data to be displayed in TableView. But I have a problem:
libc++abi.dylib: terminating with uncaught exception of type NSException
I get it after the method numberOfRowsInSection. My array is not nil, array has a 2193 elements
I do not understand why it happened
It my code for parsing JSON :
let timeStamp = NSNumber(value: Date().timeIntervalSinceNow)
var programs = [PrograToDayModel]()
override func viewDidLoad() {
super.viewDidLoad()
super.viewDidLoad()
let timeStamp = NSNumber(value: Date().timeIntervalSinceNow)
self.downloadPrograms(for: timeStamp)
}
func downloadPrograms(for timestamp: NSNumber) {
Alamofire.request("http://52.50.138.211:8080/ChanelAPI/programs/\(timestamp)").responseArray { (response: DataResponse<[PrograToDayModel]>) in
let programlArray = response.result.value
if let programlArray = programlArray {
for program in programlArray {
self.programs.append(program)
print(program.title as Any)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
it good i print element in console :
my code for table:
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
print(self.programs.count as Any)
return self.programs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProgramTableViewCell", for: indexPath) as! ProgramTableViewCell
cell.title.text = self.programs[indexPath.row].title
return cell
}
}
All identifiers in place
I using tab bar, tableView, tableViewCell
How can I solve this problem?
To identify the issue, you can just try this -
it might be a reason for that issue
So go to Main.storyboard, and right-click on View Controller at the top of the phone outline and remove any outlets with yellow flags (if any).
I was getting a similar non descriptive error when trying to initialize a uitableviewcontroller when trying to add a section/number of rows. Did you register a tableview cell class? I see that you have a custom tableview cell created, so if that isn't registered with your tableview that might be causing this error.
tableView.register("ProgramTableViewCell".self, forCellReuseIdentifier: "ProgramTableViewCell")
Related
I have a data source in this form:
struct Country {
let name: String
}
The other properties won't come into play in this stage so let's keep it simple.
I have separated ViewController and TableViewDataSource in two separate files. Here is the Data source code:
class CountryDataSource: NSObject, UITableViewDataSource {
var countries = [Country]()
var filteredCountries = [Country]()
var dataChanged: (() -> Void)?
var tableView: UITableView!
let searchController = UISearchController(searchResultsController: nil)
var filterText: String? {
didSet {
filteredCountries = countries.matching(filterText)
self.dataChanged?()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let country: Country
country = filteredCountries[indexPath.row]
cell.textLabel?.text = country.name
return cell
}
}
As you can see there is already a filtering mechanism in place.
Here is the most relevant part of the view controller:
class ViewController: UITableViewController, URLSessionDataDelegate {
let dataSource = CountryDataSource()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.tableView = self.tableView
dataSource.dataChanged = { [weak self] in
self?.tableView.reloadData()
}
tableView.dataSource = dataSource
// Setup the Search Controller
dataSource.searchController.searchResultsUpdater = self
dataSource.searchController.obscuresBackgroundDuringPresentation = false
dataSource.searchController.searchBar.placeholder = "Search countries..."
navigationItem.searchController = dataSource.searchController
definesPresentationContext = true
performSelector(inBackground: #selector(loadCountries), with: nil)
}
The loadCountries is what fetches the JSON and load the table view inside the dataSource.countries and dataSource.filteredCountries array.
Now, how can I get the indexed collation like the Contacts app has without breaking all this?
I tried several tutorials, no one worked because they were needing a class data model or everything inside the view controller.
All solutions tried either crash (worst case) or don't load the correct data or don't recognise it...
Please I need some help here.
Thank you
I recommend you to work with CellViewModels instead of model data.
Steps:
1) Create an array per word with your cell view models sorted alphabetically. If you have data for A, C, F, L, Y and Z you are going to have 6 arrays with cell view models. I'm going to call them as "sectionArray".
2) Create another array and add the sectionArrays sorted alphabetically, the "cellModelsData". So, The cellModelsData is an array of sectionArrays.
3) On numberOfSections return the count of cellModelsData.
4) On numberOfRowsInSection get the sectionArray inside the cellModelsData according to the section number (cellModelsData[section]) and return the count of that sectionArray.
5) On cellForRowAtindexPath get the sectionArray (cellModelsData[indexPath.section]) and then get the "cellModel" (sectionArray[indexPath.row]). Dequeue the cell and set the cell model to the cell.
I think that this approach should resolve your problem.
I made a sample project in BitBucket that could help you: https://bitbucket.org/gastonmontes/reutilizablecellssampleproject
Example:
You have the following words:
Does.
Any.
Visa.
Count.
Refused.
Add.
Country.
1)
SectionArrayA: [Add, Any]
SectionArrayC: [Count, Country]
SectionArrayR: [Refused]
SectionArrayV: [Visa]
2)
cellModelsData = [ [SectionArrayA], [SectionArrayC], [SectionArrayR], [SectionArrayV] ]
3)
func numberOfSections(in tableView: UITableView) -> Int {
return self.cellModelsData.count
}
4)
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionModels = self.cellModelsData[section]
return sectionModels.count
}
5)
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sectionModels = self.cellModelsData[indexPath.section]
let cellModel = sectionModels[indexPath.row]
let cell = self.sampleCellsTableView.dequeueReusableCell(withIdentifier: "YourCellIdentifier",
for: indexPath) as! YourCell
cell.cellSetModel(cellModel)
return cell
}
please barer with me that I am completely new to swift and iOS..
I'm trying to make a "team select" on my share extension. Ideally I want to be able to tap the "Team" footer and select multiple teams from a table view, and at last share/post to the selected teams.
I have been following a tutorial from 2016, but I think it is outdated by now unfortunately, and I haven't been able to find one similar that is up to date. (if you know one please link)
I have created a TeamTableViewController.swift (UITableViewController) with a hardcoded teamList which I hope to populate in the share extension.
my UITableViewController file looks like this:
import UIKit
protocol TeamViewProtocol {
func sendingViewController(viewController: TeamTableViewController, sentItem: String)
}
class TeamTableViewController: UITableViewController {
var teamList: [String] = ["Team 1", "Team 2", "Team 3", "Team 4", "Team 5"]
var delegate: TeamViewProtocol?
override func viewDidLoad() {
super.viewDidLoad()
self.clearsSelectionOnViewWillAppear = false
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.teamList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TeamCell", for: indexPath)
cell.textLabel!.text = self.teamList[indexPath.item]
return cell
}
}
My ShareViewController filer looks like this:
import UIKit
import Social
class ShareViewController: SLComposeServiceViewController, TeamViewProtocol {
var item: SLComposeSheetConfigurationItem!
var teamPickerVC: TeamTableViewController!
override func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
override func didSelectPost() {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
override func configurationItems() -> [Any]! {
self.item = SLComposeSheetConfigurationItem()
self.item.title = "Team"
self.item.value = "None"
self.item.tapHandler = {
self.teamPickerVC = TeamTableViewController()
self.pushConfigurationViewController(self.teamPickerVC)
}
return [self.item]
}
func sendingViewController(viewController: TeamTableViewController, sentItem: String) {
self.item.value = sentItem
self.popConfigurationViewController()
}
}
When I tap the extension window footer "Team" the entire extension dismisses with no error message. If however, I set the hard coded teamList array to an empty array, then the extensions does not crash/dismiss but instead shows the table view with empty rows.
What am I missing in order for my hard coded teams to show as cell/lines/rows? in the table view?
You should return the proper number of sections or can remove that method, so it will take the default value of numerOfSections as 1
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
Hope it helps
After a lot of trial and error. I finally found a forum post about the correct implementation of the tableView function that calls with the argument cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "TeamCell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "TeamCell")
}
cell!.textLabel!.text = self.teamList[indexPath.item]
return cell!
}
This was not easy to debug, and there were no error or exceptions printed.
You also have to implement the didSelectRowAt delegate for the tableView to be able to send the selected item back to the main view.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedItem = self.teamList[indexPath.item]
delegate?.sendingViewController(viewController: self, sentItem: selectedItem)
self.navigationController?.popViewController(animated: true)
}
I have this weird error message in my TableViewController class
class MenuTableViewController: UITableViewController {
fileprivate var menuItems = [MenuItem]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UINib(nibName: "MenuItemTableViewCell", bundle: nil), forCellReuseIdentifier: CELL_MENU_ITEM)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CELL_MENU_ITEM, for: indexPath) as! MenuItemTableViewCell
// this line throws the error message
if let menuItem = self.menuItems[indexPath.row].getTitle() as [MenuItem] {
cell.itemTitleLabel.text = menuItem
}
return cell
}
func setMenuItems(menuItems: [MenuItem]) {
self.menuItems = menuItems
}
}
I totally don't know what that error means. There are others facing this problem with type inout but they are doing errors with '=' instead of '==' and things like that. By the way the value of menuItems get set in another class in a completion function. But if I remove it from there I still got this error.
Since menuItems is declared as a concrete non-optional type there is no type casting nor optional binding needed.
let menuItem = self.menuItems[indexPath.row]
cell.itemTitleLabel.text = menuItem.getTitle()
The error message might be misleading. You are trying to cast (presumed) String to [MenuItem]
Maybe you want to check MenuItem? like that:
if let menuItem = self.menuItems[indexPath.row] as MenuItem {
cell.itemTitleLabel.text = menuItem.getTitle()
}
And you declare your collection with [MenuItem] type, so subscription will return non-optional value, you can remove iflet check and use:
cell.itemTitleLabel.text = self.menuItems[indexPath.row].getTitle()
I have missed to import uikit in my custom struct and get a similar error. hope it helps somebody reading here.
I am facing an issue with UITableView.
I want to dynamically fill its cells with data fetched from a remote database, so it takes some times before the data arrived.
Here is the code:
class MailBoxViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var users: [NSDictionary] = []
override func viewDidLoad() {
super.viewDidLoad()
// call to rest API code to get all users in [NSDictionary]
(...)
// set table view delegate and data source
self.tableView.delegate = self
self.tableView.dataSource = self
}
// set number of sections within table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// set number of rows for each section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return self.users.count
}
return 0
}
// set header title for each section
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Users"
}
}
// set cell content for each row
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// deque reusable cell
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
// set item title
if indexPath.section == 0 {
cell.textLabel?.text = self.users[indexPath.row]["firstname"] as? String
}
return cell
}
}
The problem is that when tableView functions are called to set number of rows for each section and to set cell content for each row, my [NSDictionary] users is still empty.
How could I do to set rows and cells only after my call to rest API code to get all users in [NSDictionary] is finished?
Thank you for any feedback.
Regards
When you get the response from the API, you should set self.users = arrayOfUsersYouReceivedFromServer and then call self.tableView.reloadData(). This
After users is populated, call tableView.reloadData(). This will call your data source methods again.
When you're done fetching the users call tableView.reloadData().
I am trying to build a list within a table view controller and I have the proper setup, but for some reason my simulator crashes at the line where I set my array. It is not an error, but a Thread issue. I'm still learning the XCode warning system so I'm not sure what that means, but I noticed that in the Thread notifications that cityArray = ([String]) 0 values. Can anyone help?
import UIKit
class ListTableViewController: UITableViewController {
var cityArray: [String] = ["Portland","San Francisco","Cupertino"]
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cityArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = self.cityArray[indexPath.row]
return cell
}
}
UPDATE:
Images of the Thread message:
try this
let cityArray: [NSArray] = ["Portland","San Francisco","Cupertino"] as NSArray
Can you also provide the error you're receiving? Is it an issue with the array being mutated while being enumerated or something?
Also,
var cityArray: [String] = ["Portland","San Francisco","Cupertino"]
can change to
var cityArray = ["Portland", "San Francisco", "Cupertino"]
Since all your objects are of the same type, the Swift's type inference takes care of this for you.