Indexing error with an array in a dictionary (Swift 3.0) - ios

I am having an issue displaying indexed objects in a table view. I have indexed the objects as a list of clients based on the first letter of their name. The indexed results are put into a dictionary like this
{Char: [Client]}
Char being the first character of the client's name and [Client] being an array of client objects, who have the first letter of their name matching the Char. When printed out, this shows up like this:
{'D': [Client("David"), Client("Dan")]}
However, when I go to set these titles in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) function, I get an index out of bounds error. The client array has a count of 3 and the contacts dictionary has a count of two, but has all 3 objects it as such:
{'S': [Client("Sam")], 'D': [Client("David"), Client("Dan")]}
How do I go through the dictionary properly to get individual clients into each table cell with the proper section headers? I am using Swift 3.0. Below I have posted how I indexed it as well as the function I am trying to override.
ClientTableViewController.swift
var clients = Client.loadAllClients()
var contacts = [Character: [Client]]()
var letters: [Character] = []
override func viewDidLoad() {
super.viewDidLoad()
letters = clients.map { (name) -> Character in
return name.lName[name.lName.startIndex]
}
letters = letters.reduce([], { (list, name) -> [Character] in
if !list.contains(name) {
return list + [name]
}
return list
})
for c in clients {
if contacts[c.lName[c.lName.startIndex]] == nil {
contacts[c.lName[c.lName.startIndex]] = [Client]()
}
contacts[c.lName[c.lName.startIndex]]!.append(c)
}
for (letter, list) in contacts {
contacts[letter] = list.sorted(by: { (client1, client2) -> Bool in
client1.lName < client2.lName
})
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Name", for: indexPath) as! ClientTableViewCell
cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName
return cell
}

Create one section per letter, by implementing numberOfSections method to return this:
return letters.count
Change code in cellForRowAt from this:
cell.clientName?.text = contacts[letters[indexPath.row]]?[indexPath.row].lName
To this:
cell.clientName?.text = contacts[letters[indexPath.section]]?[indexPath.row].lName

Related

How can I divide my table view data in sections alphabetically using Swift? (rewritten)

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
}

Data not correctly getting populated in tableview sections

I am making an app in which I need this thing in one of the screens.
I have used the tableview with sections as shown in the code below
var sections = ["Adventure type"]
var categoriesList = [String]()
var items: [[String]] = []
override func viewDidLoad() {
super.viewDidLoad()
categoryTableView.delegate = self
categoryTableView.dataSource = self
Client.DataService?.getCategories(success: getCategorySuccess(list: ), error: getCategoryError(error: ))
}
func getCategorySuccess(list: [String])
{
categoriesList = list
let count = list.count
var prevInitial: Character? = nil
for categoryName in list {
let initial = categoryName.first
if initial != prevInitial { // We're starting a new letter
items.append([])
prevInitial = initial
}
items[items.endIndex - 1].append(categoryName)
}
for i in 0 ..< count
{
var tempItem = items[i]
let tempSubItem = tempItem[0]
let char = "\(tempSubItem.first)"
sections.append(char)
}
}
func getCategoryError(error: CError)
{
print(error.message)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sections[section]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = categoryTableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
cell.textLabel?.text = self.items[indexPath.section][indexPath.row]
return cell
}
But it is producing runtime errors on return self.items[section].count
The reason for this error is because I am loading data (items array) is from server and then populating sections array after it. At the time when tableview gets generated, both the sections and items array is empty. That is why error occurs.
I am new to iOS and not getting grip over how to adjust data in sections of tableview.
Can someone suggest me a better way to do this?
What should be number of rows in section when I have no idea how much items server call will return?
Also i want to cover the case when server call fails and no data is returned. Would hiding the tableview (and showing error message) be enough?
Any help would be much appreciated.
See if this works: Make your data source an optional:
var items: [[String]]?
And instantiate it inside your getCategorySuccess and fill it with values. Afterwards call categoryTableView.reloadData() to reload your table view.
You can add a null check for your rows like this:
return self.items?[section].count ?? 0
This returns 0 as a default. Same goes for number of sections:
return self.items?.count ?? 0
In case the call fails I would show an error message using UIAlertController.
Your comment is incorrect: "At the time when tableview gets generated, both the sections and items array is empty. That is why error occurs."
According to your code, sections is initialized with one entry:
var sections = ["Adventure type"]
This is why your app crashes. You tell the tableview you have one section, but when it tries to find the items for that section, it crashes because items is empty.
Try initializing sections to an empty array:
var sections = [String]()
Already things should be better. Your app should not crash, although your table will be empty.
Now, at the end of getCategorySuccess, you need to reload your table to reflect the data retrieved by your service. Presumably, this is an async callback, so you will need to dispatch to the main queue to do so. This should work:
DispatchQueue.main.async {
self.categoryTableView.reloadData()
}

Creating a nested array from a single array

I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.
So I have this array which is the filtered data out of the fetchedResultsController:
filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
}))!
How can I make an array called filteredObjects which sorts my items for sections? For example
- Section 1 ( filteredObjects[0] ):
item 1 ( filteredObjects[0][1] )
item 2 ( filteredObjects[0][2] )
-
Section 2 ( filteredObjects[1] ):
item 1 ( filteredObjects[1][0] )
etc
Use below method to define number of sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return filteredObjects.count
}
And, for number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredObjects[section].count
}
And Finally, for CellForRowAtIndexpath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell
let currentItem = filteredObjects[indexPath.section][indexPath.row]
... Here, use currentItem as whatever it is (Object or dictionary)
return cell
}
let budgets = [Budget]()
let searchResult = [Budget]()
You should always use searchResult array in tableview datasource methods. initially you should add all objects of budgets array to searchResult & load table view.
when search started remove all items from searchResult and add filtered result to search result array & reload tableview.
func search(searchText:String){
searchResult.removeAll()
let result = budgets.filter({
var budget = $0
let filtered = budget.expenses.filter({
if let deptName = $0.deptName{
return deptName.lowercased().contains(searchText.lowercased())
}
return false
})
budget.expenses = filtered
return budget.expenses.count != 0
})
searchResult.append(contentsOf: result)
}
struct Budget {
var expenses = [Expense]()
}
struct Expense{
var deptName:String?
}

Setting one parse object of type array to a tableView

I know that I can query for, lets say, users that have emailVerified equal to true and present them into a tableView, but I was having trouble getting a single Parse object of type array into a tableView. I couldn't find anything online about this specific problem, but after putting a few answers together, I got it to work my answer is below for those also having trouble with this.
Here is what I found based on my question. I have an object in Parse called "my_classes" that is of type array. I want to get the items from the array into a tableView.
1) Create a variable: var myClassesResults : NSMutableArray = []
2) Create the function or place the code where necessary:
func getUserData() {
if PFUser.currentUser()!.objectForKey("my_classes") != nil {
let classes = PFUser.currentUser()!.objectForKey("my_classes")!
myClassesResults = classes as! NSMutableArray
self.noClasses = false
self.tableView.reloadData()
} else {
self.noClasses = true
self.tableView.reloadData()
}
}
3) tableView functions:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myClassesResults.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel!.text = myClassesResults[indexPath.row] as? String
return cell
}

How to add list of songs with sections to UITableView using Swift?

I'm trying to create a simple music player that lists all the songs on my device in a UITableView split into alphabetic sections (like the Apple Music Player).
There are two areas I can't figure out:
Getting the number of songs per section so that I can create the
correct number of rows in my table for each section
Accessing the items in each section to populate the section cells
My code is already pretty long so I'll put the pertinent info here:
I get the list of songs like this:
let songsQry:MPMediaQuery = MPMediaQuery.songsQuery()
This is where I'm unsure:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//How can I get the number of songs per Section to return??
// this does not work:
return songsQry.itemSections![0].count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
//How do I get the song for the Section and Row??
cell.textLabel?.text = ????
return cell
}
I'm going to answer my own question.
I've posted similar questions here on SO and everyone replying said this couldn't be done and that additional Arrays were needed plus custom sort routines. That's simply not true.
Note however, that in my example code I show how get the same kind of results for an Album Query. The code for an Artist query is almost identical.
This code uses the return from an Album Query to:
1) Build a TableView index
2) Add Albums by Title (using Apple's sorting) to table Sections
3) Start playing an album when selected
Here's the Swift code to prove it:
// Set up a basic Albums query
let qryAlbums = MPMediaQuery.albumsQuery()
qryAlbums.groupingType = MPMediaGrouping.Album
// This chunk handles the TableView Index
//create index title
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
let sectionIndexTitles = qryAlbums.itemSections!.map { $0.title }
return sectionIndexTitles
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return index
}
// This chunk sets up the table Sections and Headers
//tableview
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return (qryAlbums.itemSections![section].title)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return (qryAlbums.itemSections?.count)!
}
// Get the number of rows per Section - YES SECTIONS EXIST WITHIN QUERIES
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return qryAlbums.collectionSections![section].range.length
}
// Set the cell in the table
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// i'm only posting the pertinent Album code here.
// you'll need to set the cell details yourself.
let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
let rowItem = qryAlbums.collections![indexPath.row + currLoc]
//Main text is Album name
cell.textLabel!.text = rowItem.items[0].albumTitle
// Detail text is Album artist
cell.detailTextLabel!.text = rowItem.items[0].albumArtist!
// Or number of songs from the current album if you prefer
//cell.detailTextLabel!.text = String(rowItem.items.count) + " songs"
// Add the album artwork
var artWork = rowItem.representativeItem?.artwork
let tableImageSize = CGSize(width: 10, height: 10) //doesn't matter - gets resized below
let cellImg: UIImageView = UIImageView(frame: CGRectMake(0, 5, myRowHeight-10, myRowHeight-10))
cellImg.image = artWork?.imageWithSize(tableImageSize)
cell.addSubview(cellImg)
return cell
}
// When a user selects a table row, start playing the album
// This assumes the myMP has been properly declared as a MediaPlayer
// elsewhere in code !!!
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
myMP.setQueueWithItemCollection(qryAlbums.collections![indexPath.row + currLoc])
myMP.play()
}
Also, here's a few helpful notes:
1) List all the Albums from the query:
for album in allCollections!{
print("---------------")
print("albumTitle \(album.items[0].albumTitle)")
print("albumTitle \(album.representativeItem?.albumTitle)")
print("albumTitle \(album.representativeItem?.valueForProperty(MPMediaItemPropertyAlbumTitle))")
} // each print statement is another way to get the title
2) Print out part of the query to see how it's constructed:
print("xxxx \(qryAlbums.collectionSections)")
I hope this helps some of you - if so up vote!
The idea is simple:
You need to create a sorted array GroupedSongs which holds objects
of type [String: [MPMediaItem]] (key is the character and
the array holds the songs corresponding that character). The
[MPMediaItem] array must be sorted from the title property.
Setting up the Table View Datasource
For each key we need a section which now is the main array
For each item we need a number a songs, so this will be the number
of rows for our tableView
Implementation
Code has comments so no more talking :D
var items: [[String: [MPMediaItem]]] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
items = loadSongsDividedByTitle()
}
// MARK: - Delegation
// MARK: Table view datasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let object: [String: [MPMediaItem]] = items[section]
let key = Array(object.keys)[0] // We always have one object there
let songs: [MPMediaItem] = object[key]!
return songs.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
// Load song from the array
let object: [String: [MPMediaItem]] = items[indexPath.section]
let key = Array(object.keys)[0] // We always have one object there
let songs: [MPMediaItem] = object[key]!
let song = songs[indexPath.row]
// Bind title of the song to the cell text label
cell.textLabel?.text = song.title
return cell
}
// MARK: - Helpers
func loadSongsDividedByTitle() -> [[String: [MPMediaItem]]] {
guard var songs = MPMediaQuery.songsQuery().items else { return [] }
// Sort songs
songs = songs.sort({$0.title < $1.title})
// Create a new dictionary to hold array of words for each letter
var object: [String: [MPMediaItem]] = [:]
// Songs holding a dictionary with music
var groupedSongs : [[String: [MPMediaItem]]] = []
// Enumerate in words
for mediaItem in songs {
guard let title: String = mediaItem.title! else { continue } // If we don't have the title skip the song
// Use the first character as a key for each array
let key = String(title.characters.first!)
if var songGroup = object[key] {
// If we have an array, then append the new word there
songGroup.append(mediaItem)
object[key] = songGroup
} else {
// Create an array for that key
object[key] = [mediaItem]
}
}
// Add every object into one big array
for (key, value) in object {
let sortedSongs = value.sort({$0.title < $1.title})
groupedSongs.append([key: sortedSongs])
}
// Sort it alphabetically from a-z
groupedSongs = groupedSongs.sort({Array($0.keys)[0] < Array($1.keys)[0]})
return groupedSongs
}
Playground output with strings

Resources