Cells won't load when using multiple collection views - swift

I have two collection views that get their data from two arrays that append from a url session function. I deleted everything and started over and I get that same problem. I added a breakpoint and the arrays are getting filled. I also saw on other solutions, reloadData() was used after the array is filled but doesn't work for me
HomeViewController:
//Variable declarations
var recentlyPlayed = [RecentlyPlayed]()
private var info = UserDefaults.standard.dictionary(forKey: "parseJSON")
var userLikedSongs = [LikedSongs]()
var refreshControl: UIRefreshControl!
#IBOutlet weak var LikedSongsCollectionView: UICollectionView!
#IBOutlet weak var RecentlyPlayedCollectionView: UICollectionView!
#IBOutlet weak var scrollView: UIScrollView!
//Once view has loaded
override func viewDidLoad() {
super.viewDidLoad()
//Assign Collection views to self
RecentlyPlayedCollectionView.delegate = self
RecentlyPlayedCollectionView.dataSource = self
LikedSongsCollectionView.delegate = self
LikedSongsCollectionView.dataSource = self
// Get user id and users recently played songs
let user = getId()
let id = Int(user)!
retriveRecentSongs(info: id)
retriveLikedSongs(info: id)
RecentlyPlayedCollectionView.reloadData()
LikedSongsCollectionView.reloadData()
//Hide navigation bar
self.navigationController?.isNavigationBarHidden = true
}
// Define Recent songs collection view count
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(collectionView == RecentlyPlayedCollectionView) {
return recentlyPlayed.count
} else {
return userLikedSongs.count
}
}
//Set content inside recently collection view cells
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
if (collectionView == LikedSongsCollectionView) {
let likeCell = collectionView.dequeueReusableCell(withReuseIdentifier: "LikedCell", for: indexPath) as! LikedSongsCollectionViewCell
likeCell.LikedData = userLikedSongs[indexPath.row]
return likeCell
} else {
let recentCell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecentlyPlayedCell", for: indexPath) as! RecentlyPlayedCollectionViewCell
recentCell.Recentdata = recentlyPlayed[indexPath.row]
return recentCell
}
}
//Get users recenlty played song with URL session
func retriveRecentSongs(info: Int) {
let url = URL(string: "http://127.0.0.1/musicfiles/getRecentlyPlayed.php?info=" + String(info))
URLSession.shared.dataTask(with: url!) { data, response, error in
let retrievedList = String(data: data!, encoding: String.Encoding.utf8)
print(retrievedList!)
self.parseRecentSongs(data: retrievedList!)
}
.resume()
print("Getting songs")
}
func parseRecentSongs (data: String) {
if (data.contains("*")) {
let dataArray = (data as String).split(separator: "*").map(String.init)
for item in dataArray {
let itemData = item.split(separator: ",").map(String.init)
let newSong = RecentlyPlayed(id: itemData[0], songName: itemData[1], trackName: itemData[2], artist: itemData[3], owner: itemData[4], cover: itemData[5])
recentlyPlayed.append(newSong)
}
}
}
Also can add RecentlyPlayedCollectionViewCell and LikedSongsCollectionView if needed.

Your function retriveRecentSongs contains an asynchronous closure. That means code inside it continues to execute even after it's called and returned.
func retriveRecentSongs(info: Int) {
let url = URL(string: "http://127.0.0.1/musicfiles/getRecentlyPlayed.php?info=" + String(info))
/// See here!
URLSession.shared.dataTask(with: url!) { data, response, error in
let retrievedList = String(data: data!, encoding: String.Encoding.utf8)
print(retrievedList!)
self.parseRecentSongs(data: retrievedList!)
}
.resume()
print("Getting songs")
}
You might notice how print("Getting songs") is printed before print(retrievedList!).
When "Getting songs" is printed, you've only just started the URL task, and the download hasn't completed yet. At this point, recentlyPlayed is still empty.
retriveRecentSongs(info: id) /// started the download
RecentlyPlayedCollectionView.reloadData() /// but at this point, has not completed yet.
You need to call reloadData once the download has finished.
func retriveRecentSongs(info: Int) {
let url = URL(string: "http://127.0.0.1/musicfiles/getRecentlyPlayed.php?info=" + String(info))
URLSession.shared.dataTask(with: url!) { data, response, error in
let retrievedList = String(data: data!, encoding: String.Encoding.utf8)
print(retrievedList!)
/// ok, the download finished, parse the songs
self.parseRecentSongs(data: retrievedList!)
}
.resume()
print("Getting songs")
}
func parseRecentSongs (data: String) {
if (data.contains("*")) {
let dataArray = (data as String).split(separator: "*").map(String.init)
for item in dataArray {
let itemData = item.split(separator: ",").map(String.init)
let newSong = RecentlyPlayed(id: itemData[0], songName: itemData[1], trackName: itemData[2], artist: itemData[3], owner: itemData[4], cover: itemData[5])
recentlyPlayed.append(newSong)
}
}
/// now, do reloadData.
RecentlyPlayedCollectionView.reloadData()
}
Also make sure you delete
RecentlyPlayedCollectionView.reloadData()
LikedSongsCollectionView.reloadData()
inside viewDidLoad().

Related

CollectionView Reloaddata - Fatal error: Index out of range

I add the data that I have drawn from Database to CollectionView. I am putting the data I have added as an array in the model array. I see the data inside Array in collectionView. Sometimes data is added smoothly but sometimes I get the error
"Thread 1: Fatal error: Index out of range"
. Sometimes while working sometimes why not? I think there is a problem with collectionView.reloadData ().
enter image description here
#IBOutlet weak var sonsuzCollec: UICollectionView!
var model = [[String]]()
var davetiyefilee = [String]()
var davetiyefilee2 = [String]()
extension denemeView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
if (collectionView == sonsuzCollec) {
return model[section].count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
if (collectionView == sonsuzCollec) {
return yeniDavKATIsımNew.count
}
return 0
}
...
}
#objc func davetiyeCEK1() {
if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
for review in baslik {
if let soru_baslik = review["davetiyefilee"] as? String {
let s = String(describing: soru_baslik)
self.davetiyefilee.append(s)
}
}
self.model.append(self.davetiyefilee)
DispatchQueue.main.async { [weak self] in
self?.sonsuzCollec?.reloadData()
}
}
}
#objc func davetiyeCEK2() {
if let baslik = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
for review in baslik {
if let soru_baslik = review["davetiyefilee"] as? String {
let s = String(describing: soru_baslik)
self.davetiyefilee2.append(s)
}
}
self.model.append(self.davetiyefilee2)
DispatchQueue.main.async { [weak self] in
self?.sonsuzCollec?.reloadData()
}
}
}
i think it is beacuse of your model array's section item is empty.
how many collection you are using? can you show more full code
or maybe another approch is in your numberofsection try this
if (collectionView == sonsuzCollec) {
var numberofRows = 0
if model[section].count > 0 {
numberofRows = model[section].count
} else {
numberofRows = 0
}
return numberofRows
}

UITextfield showing empty row in UITableView using insert

I have a chat feature on my app that updates the table instantly when a user enters new text. Unfortunately when a user enters the text it shows any empty row in the uitableview. When I exit out of the screen and return that new value is now there at the end of the table. So even though it's showing an empty row in the uitableview it's submitting the actual value to the database.
class ConversationViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {
//var user = NSDictionary()
var messages = NSDictionary()
var hhmessages = [AnyObject]()
//var messages: [Message] = []
var pictures = [UIImage]()
var avas = [UIImage]()
var avaURL = [String]()
var isLoading = false
var skip = 0
var limit = 50
var images = [UIImage]()
var incoming: [Int] = []
var comments = [String]()
var ids = [String]()
#IBOutlet var replyTxt: UITextView!
#IBOutlet var replyTxt_height: NSLayoutConstraint!
#IBOutlet var replyTxt_bottom: NSLayoutConstraint!
#IBOutlet var replyBtn: UIButton!
var commentsTextView_bottom_identity = CGFloat()
#IBOutlet var tableView: UITableView!
// Table View here + basic configuration
override func viewDidLoad() {
super.viewDidLoad()
// dynamic cell height
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
loadPosts()
replyTxt.layer.cornerRadius = replyTxt.bounds.width / 50
replyTxt.backgroundColor = UIColor.clear
replyTxt.layer.borderColor = UIColor.gray.cgColor
replyTxt.layer.borderWidth = 1.0
let username = messages["sender"] as? String
self.navigationItem.title = username
}
// TABLEVIEW
// Number os cells
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hhmessages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let colorSmoothGray = UIColor(red: 229/255, green: 229/255, blue: 234/255, alpha: 1)
let colorBrandBlue = UIColor(red: 148 / 255, green: 33 / 255, blue: 147 / 255, alpha: 1)
let pictureURL = hhmessages[indexPath.row]["uploadpath"] as? String
// no picture in the post
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ConversationCell
cell.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
// shortcuts
let hhpost = hhmessages[indexPath.row]
let text = hhpost["messagetext"] as? String
cell.messageLbl.text = text
return cell
}
// func of loading posts from server
#objc func loadPosts() {
//isLoading = true
let me = user!["username"] as! String
let meid = user!["id"] as! String
print(meid)
print(me)
//print(username)
let uuid = messages["uuid"] as! String
print(uuid)
// accessing php file via url path
let url = URL(string: "http://localhost/message.php")!
// pass information to php file
let body = "username=\(me)&uuid=\(uuid)&recipient_id=\(meid)"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body.data(using: String.Encoding.utf8)
tableView.transform = CGAffineTransform(rotationAngle: -(CGFloat)(Double.pi));
// launch session
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
// no error of accessing php file
// error occured
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
//self.isLoading = false
return
}
do {
// access data - safe mode
guard let data = data else {
Helper().showAlert(title: "Data Error", message: error!.localizedDescription, in: self)
//self.isLoading = false
return
}
// getting content of $returnArray variable of php file
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
// accessing json data - safe mode
guard let posts = json?["messages"] as? [NSDictionary] else {
//self.isLoading = false
return
}
// assigning all successfully loaded posts to our Class Var - posts (after it got loaded successfully)
self.hhmessages = posts
self.tableView.reloadData()
// scroll to the latest index (latest cell -> bottom)
let indexPath = IndexPath(row: self.hhmessages.count - 1, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
// self.isLoading = false
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
//self.isLoading = false
return
}
}
}.resume()
}
// function sending requset to PHP to uplaod a file
func uploadPost() {
// validating vars before sending to the server
guard let user_id = user?["id"] as? String, let username = user?["username"] as? String, let avaPath = user?["ava"] else {
// converting url string to the valid URL
if let url = URL(string: user?["ava"] as! String) {
// downloading all data from the URL
guard let data = try? Data(contentsOf: url) else {
return
}
// converting donwloaded data to the image
guard let image = UIImage(data: data) else {
return
}
// assigning image to the global var
let currentUser_ava = image
}
return
}
let user_id_int = Int(user_id)!
let messagetext = replyTxt.text.trimmingCharacters(in: .whitespacesAndNewlines)
hhmessages.insert(messagetext as AnyObject, at: hhmessages.endIndex)
let indexPath = IndexPath(row: hhmessages.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
tableView.transform = CGAffineTransform(rotationAngle: -(CGFloat)(Double.pi));
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
replyTxt.text = ""
textViewDidChange(replyTxt)
let recipient = messages["username"] as! String
let rid = String(describing: messages["recipient_id"]!)
let uuid = messages["uuid"] as! String
puuid = UUID().uuidString
// prepare request
let url = URL(string: "http://localhost/messagepost.php")!
let body = "sender_id=\(user_id)&sender=\(username)&text=\(messagetext)&recipient_id=\(rid)&recipient=\(recipient)&uuid=\(uuid)&puuid=\(puuid)"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = body.data(using: .utf8)
// send request
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
// error happened
if error != nil {
Helper().showAlert(title: "Server Error", message: error!.localizedDescription, in: self)
return
}
do {
// converting received data from the server into json format
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
// safe mode of casting json
guard let parsedJSON = json else {
return
}
// if the status of JSON is 200 - success
if parsedJSON["status"] as! String == "200" {
} else {
Helper().showAlert(title: "400", message: parsedJSON["status"] as! String, in: self)
return
}
// json error
} catch {
Helper().showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
return
}
}
}.resume()
}
#IBAction func replyBtn_clicked(_ sender: Any) {
if replyTxt.text.isEmpty == false && replyTxt.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false {
uploadPost()
//tableView.reloadData()
}
}
While appending a new message you are adding a String to the hhmessages array
let messagetext = replyTxt.text.trimmingCharacters(in: .whitespacesAndNewlines)
hhmessages.insert(messagetext as AnyObject, at: hhmessages.endIndex)
But in cellForRowAt method you are trying to get the String from hhmessages array using "messagetext" key
let pictureURL = hhmessages[indexPath.row]["uploadpath"] as? String
let hhpost = hhmessages[indexPath.row]
let text = hhpost["messagetext"] as? String
Change
hhmessages.insert(messagetext as AnyObject, at: hhmessages.endIndex)
to
hhmessages.insert(["messagetext": messagetext] as AnyObject, at: hhmessages.endIndex)
Instead of using array of AnyObject, use a struct
var hhmessages = AnyObject
struct Message {
var uploadpath: URL?
var messagetext: String?
}
var hhmessages = [Message]()

Stripe Alamofire JSON not populating array

I am trying to populate a UITableView with a list of credit cards in Stripe. I know it works for my test environment because I am able to see a JSON response from Postman. It for some reason is not populating my table.
Since this is an [Any Object] I do not need to create a separate class with init stings? I have other tables in my app populating data and updated UILabels after pulling info from FireBase.
Here is the code in the PaymentsVC.swift View Controller:
class PaymentVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var headerView: UIView!
#IBOutlet var cardsTableView: UITableView!
#IBOutlet var cardTextField: STPPaymentCardTextField!
var stripeTool = StripeTools()
static let sharedClient = MyAPIClient()
//var customerId: String?
let customerId = "mycusid"
var baseURLString: String? = "https://api.sripe.com/v1/customers"
var baseURL: URL {
if let urlString = self.baseURLString, let url = URL(string: urlString) {
return url
} else {
fatalError()
}
}
var stripeUtil = StripeUtil()
var cards = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//only one section
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cards.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let url = self.baseURL.appendingPathComponent("\(self.customerId)/sources?object=card")
let headers = ["Authorization": self.stripeTool.getBasicAuth()]
Alamofire.request(url, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success(let result):
if let cards = STPCustomer.decodedObject(fromAPIResponse: result as? [String: AnyObject]) {
print(cards)
// completion(cards, nil)
} else {
// completion(nil, NSError.customerDecodingError)
}
case .failure(let error): break
// nil, error
}
}
//get card cell with cardCell identifier don't forget it on your storyboard
let cell = tableView.dequeueReusableCell(withIdentifier: "cardCell") as! CardCell
//get the last4 value on the card json, create the string and pass it to the label
if let last4 = self.cards[indexPath.row]["last4"] {
cell.cardNumberLabel.text = "**** **** **** \(last4!)"
}
//get the month/year expiration values on the card json, create the string and pass it to the label
if let expirationMonth = self.cards[indexPath.row]["exp_month"], let expirationYear = self.cards[indexPath.row]["exp_year"] {
cell.expirationLabel.text = "\(expirationMonth!)/\(expirationYear!)"
}
return cell
}
Don't put api calls inside cellForRowAt as it'll be called every cell creation/dequeuing, you need to put this code inside viewDidLoad , with reloading the table
let url = self.baseURL.appendingPathComponent("\(self.customerId)/sources?object=card")
let headers = ["Authorization": self.stripeTool.getBasicAuth()]
Alamofire.request(url, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success(let result):
if let cards = STPCustomer.decodedObject(fromAPIResponse: result as? [String: AnyObject]) {
print(cards)
self.cards = cards
self.cardsTableView.reloadData()
// completion(cards, nil)
} else {
// completion(nil, NSError.customerDecodingError)
}
case .failure(let error): break
// nil, error
}
}
don't forget to set in viewDidLoad
self.cardsTableView.delegate = self
self.cardsTableView.dataSource = self

Can any one help me to solve this error using Swift

would you please help me to solve this error .I'am trying to download an Image From Firebase Database, this is my code and I put a snapshot for the error . ThanksThis is a snapshot for the error in Xcode
import UIKit
import FirebaseDatabase
class ViewController: UIViewController , UITableViewDataSource , UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
var ref:FIRDatabaseReference?
var Handle:FIRDatabaseHandle?
var myClass = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
ref=FIRDatabase.database().reference()
Handle = ref?.child("Posts").observe(.childAdded, with: { (snapshot) in
let post = snapshot.valueInExportFormat()
for url in post! as! [Post] { // Error Here
self.myClass.append(url)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return myClass.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)as? TableViewCell{
cell.MyImage.alpha = 0
cell.textLabel?.text = PostData[indexPath.row]
DispatchQueue.main.async(execute: {
let imgurl = URL(string : self.myClass [(indexPath as NSIndexPath).row].url)
let imgdata = NSData(contentsOf: imgurl!)
cell.MyImage.image = UIImage(data: imgdata as! Data)
UIView.animate(withDuration: 0.5, animations: {
cell.MyImage.alpha = 1
})
})
return cell
} else {
let cell = TableViewCell()
DispatchQueue.main.async(execute: {
let imgurl = URL(string : self.myClass [(indexPath as NSIndexPath).row].url)
let imgdata = NSData(contentsOf: imgurl!)
cell.MyImage.image = UIImage(data: imgdata as! Data)
})
return cell
}
}
}
})
}
Sometimes simple is the way to go.
assume you have a Firebase structure
Planets
planet_4
some_text = "My post about Mars"
image_url = "images/mars.jpg"
planet_2
some_text = "My post about Venus"
image_url = "images/venus.jpg"
and suppose we want to load each text and image and display in a tableview. We can do it one of two ways, one at a time with .childAdded or all at once with .value. In this example, we'll walk through them one at a time.
let planetsRef = myRootRef.child("Planets")
planetsRef.observe(.childAdded, with: { snapshot in
let dict = snapshot.value as! [String: AnyObject]
let text = dict["text"]
let imageUrl = dict["image_url"]
// Create a reference to the file you want to download
let planetRef = storageRef.child(imageUrl) //storageRef is defined elsewhere
// Download in memory with a maximum allowed size
// of 1MB (1 * 1024 * 1024 bytes)
planetRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
if (error != nil) {
// Got an error so handle it
} else {
// Data for "images/some planet.jpg" is returned
// let planetImage: UIImage! = UIImage(data: data!)
// then add the text and the image to your dataSource array
// and reload your tableview.
}
})
})
This is not tested but will provide the general idea
Maybe you want:
for url in post! {
var wrappedPost = Post()
wrappedPost.url = url
... use wrappedPost for whatever you need a Post object for
}

Remote Data won't show on tableView

I'm clueless as to what is wrong. My console doesn't give me any errors, my code seems fine but nothing is showing up. Could someone check my code, see why it doesn't want to work? My tableView is connected with its delegates and source. Not sure what is the problem.
Here is my code:
private let cellIdentifier = "cell"
private let apiURL = "api link"
class TableView: UITableViewController {
//TableView Outlet
#IBOutlet weak var LegTableView: UITableView!
//API Array
var legislatorArray = [congressClass]()
func getLegislators (fromSession session: NSURLSession) {
//Calling url
if let jsonData = NSURL(string: apiURL) {
// Requesting url
let task = session.dataTaskWithURL(jsonData) {(data, response, error) -> Void in
//Check for errors
if let error = error {print(error)
} else {
if let http = response as? NSHTTPURLResponse {
if http.statusCode == 200 {
//Getting data
if let data = data {
do {
let legislatorData = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
//Get API data
if let getData = legislatorData as? [NSObject:AnyObject],
findObject = getData["results"] as? [AnyObject]{
//Return data
for cellFound in findObject{
if let nextCell = cellFound["results"] as? [NSObject:AnyObject],
name = nextCell["first_name"] as? String,
lastName = nextCell["last_name"] as? String,
title = nextCell["title"] as? String,
partyRep = nextCell["party"] as? String,
position = nextCell ["position"] as? String,
id = nextCell ["bioguide_id"] as? String
{
//Add data to array
let addData = congressClass(name: name, lastName: lastName, title: title, party: partyRep, position: position, bioID: id)
self.legislatorArray.append(addData)
}
}//end cellFound
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.reloadData()
}
}
}
//end do
catch {print(error)}
}//end data
}//end statusCode
}//end http
}//else
}//end task
//Run code
task.resume()
}//end jsonData
}
override func viewDidLoad() {
super.viewDidLoad()
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: sessionConfig)
getLegislators(fromSession: urlSession)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
//TableView Rows
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return legislatorArray.count
//return 5
}
//Cell Configuration
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CellTableView
cell.lesName?.text = legislatorArray[indexPath.row].name + " " + legislatorArray[indexPath.row].lastName
cell.lesTitle?.text = legislatorArray[indexPath.row].title
cell.lesParty?.text = legislatorArray[indexPath.row].party
//These tests worked fine.. the tableView is working. But the data doesn't seem to pass.
//cell.lesName.text = "Name" + " " + "lastName"
//cell.lesTitle.text = "Title goes here"
//cell.lesParty.text = "D"
return cell
}
}
You're not reloading the tableView
The problem is in this piece of code
//-----------------------------
//New empty array for api data
var indexPath:[NSIndexPath] = []
//Adding data to new array
for i in 0..<self.legislatorArray.count{
let secondIndexPath = NSIndexPath(forRow: i, inSection: 0)
indexPath.append(secondIndexPath)
}
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.insertRowsAtIndexPaths(indexPath, withRowAnimation: .Left)
}
You don't need any of that. You can just reload the tableView as follows:
//Adding data to table
dispatch_async(dispatch_get_main_queue()) { () -> Void in
//You only need to reload it and that should do the trick
self.tableView.reloadData()
}
I know you said your tableView is connected to the delegate and dataSource but it's not showing in your code.
You conformed the ViewController to the correct protocols but you need something like this in your viewDidLoad.
self.tableView.deletage = self
self.tableView.dataSource = self
//I don't know if this was a typo but in your cellForRowAtIndexPath you are using CellTableView
let nibName = UINib(nibName: "CellTableView", bundle:nil)
self.tableView.registerNib(nibName, forCellReuseIdentifier: cellIdentifier)
I created an example of a better design for your implementation
This is for the WebService and your Custom Class
https://github.com/phantomon/Stackoverflow/blob/master/SO1/MyTableView/MyTableView/Models/WebServiceManager.swift
This is for the ViewController with your tableView
https://github.com/phantomon/Stackoverflow/blob/master/SO1/MyTableView/MyTableView/ViewController.swift
You just need to modify the UITableViewCell with your custom one.
And of course review your custom class data.