I am pretty new to Xcode and Swift. I am trying to display data (restaurants names) in alphabetical order in TableView. I have a JSON file that sorts each restaurant into the correct neighborhood.The code works perfectly in the view controller where I m displaying the name of the neighborhood in sections and the name of the restaurant in rows. My problem is that I am trying to sort all the restaurants names in a different view controller where the sections display the Alphabet (A,B,C...) and under each sections I am trying to display the restaurants alphabetically with index on the side. Something similar to the Contact App on the iPhone but instate of contact names I need to show the restaurant names. Hope I make sense. My code looks like this:
class BarsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SWRevealViewControllerDelegate, UISearchBarDelegate {
@IBOutlet var btnMenuButton: UIBarButtonItem!
@IBOutlet var tableView: UITableView!
@IBOutlet var searchButton: UIBarButtonItem!
var noDataLabel = UILabel()
let urlString = "http://barhoppersf.com/json/neighborhoods.json"
var restaurantArray = Array<Restaurant>()
var filteredRestaurants = [Restaurant]()
var shouldShowSearchResults = false
var searchBar = UISearchBar()
var logoImageView: UIImageView!
let restaurantsName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let indexName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let voidIndex = [""]
var restSections = [String]()
var restDictionary = [String : [String]]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL() // This loads tableview with data from url
tableView.reloadData()
}
**//JSON FUNC**
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
guard let json = try? JSONSerialization.jsonObject(with: data) else { return }
guard let dict = json as? Dictionary<String,Dictionary<String,Dictionary<String,Array<Dictionary<String,String>>>>> else { return }
guard let hoods = dict["hoods"] else { return }
guard let names = hoods["neighborhoodNames"] else { return }
for (key, value) in names {
let neighborhood = NeighborhoodRestaurants(name: key, data: value)
self.tableData.append(neighborhood)
self.tableData.sort { $0.name < $1.name }
self.filteredRestaurants = self.tableData
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.restaurantArray[section].restaurants.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.restaurantArray[section].name
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.rowHeight = 40
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RestaurantsTableViewCell
cell.barLabel.text = self.restaurantArray[indexPath.section].restaurants[indexPath.row].name
return cell
}
I have a separate swift file with all the structure for the JSON
struct Restaurant {
var name: String
var cuisine: String
var hours: String
var description: String
var address: String
var phone: String
var website: String
var sports: String
var image: String
init?(dict:Dictionary<String,String>) {
guard
let name = dict["name"],
let cuisine = dict["cuisine"],
let hours = dict["hours"],
let description = dict["description"],
let address = dict["address"],
let phone = dict["phone"],
let website = dict["website"],
let sports = dict["sports"],
let image = dict["image"]
else {
return nil
}
self.name = name
self.cuisine = cuisine
self.hours = hours
self.description = description
self.address = address
self.phone = phone
self.website = website
self.sports = sports
self.image = image
}
//MARK: Function for the data from ViewControler
}
struct NeighborhoodRestaurants {
var name: String
var restaurants: Array<Restaurant>
init(name:String, data:Array<Dictionary<String,String>>) {
self.name = name
self.restaurants = Array<Restaurant>()
for dict in data {
if let restaurant = Restaurant(dict: dict) {
self.restaurants.append(restaurant)
self.restaurants.sort { $0.name < $1.name }
}
}
}
}
This is the JSON file: http://barhoppersf.com/json/neighborhoods.json
This is a image of the neighborhoods view controller that works great. You can get the idea! Thanks again in advance!!