values of tableview cell are mixing - swift

when i tap on the accept button in a cell of view controller its always sends the same value to next controller
class FriendRequestTVC: UITableViewCell {
struct GB{
static var senderID = 0
}
this is how im saving response
class RequestResponseVC : UIViewController{
var requests:[[String:Any]] = [[String:Any]] ()
switch response.result {
case .success:
if let responseValue = response.value as! [String:Any]? {
if let responseData = responseValue["data"] as! [[String:Any]]?{
self.requests = responseData
self.tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FriendRequestTVC
let data = self.requests[indexPath.row]
FriendRequestTVC.GB.senderID = self.requests[indexPath.row]["id"] as! Int
return cell
}
it always sends the same value to the var in struct
suggest me how i save the senderID that it remains different for every cell according to their array.

Related

Cell casting throws exception

I am trying to load information to a tableView, and I get an exception because some information in the cell isn't initialized when I cast to it. and this is my code :
The code for the view containing the tableView:
private func populateActiveChats()
{
let loggedOnUserID = Auth.auth().currentUser?.uid
let ref = Constants.refs.databaseChatsLite.child(loggedOnUserID!)
ref.observe(.value, with:
{ (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot]
{
if (self.chatsDictionary.keys.contains(child.key) == false)
{
let chatValueDictionary = child.value as? NSDictionary
self.AddChatToCollections(chatAsDictionary: chatValueDictionary)
self.DispatchQueueFunc()
}
}
})
}
func AddChatToCollections(chatAsDictionary: NSDictionary!)
{
if chatAsDictionary == nil
{
return
}
let contactName =
chatAsDictionary[Constants.Chat.ChatRoomsLite.CONTACT_NAME] as! String
let newMsgs = chatAsDictionary[Constants.Chat.ChatRoomsLite.NUM_OF_UNREAD_MSGS] as! Int
let contactID = chatAsDictionary[Constants.Chat.ChatRoomsLite.CONTACT_ID] as! String
let chatToAdd = PrivateChatLiteObject(chattingWith: contactName, ContactID: contactID, unreadMessages: newMsgs, LastMSG: "")
chatsDictionary[contactID] = chatToAdd
chatsIndex.append(contactID)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = ChatsTableView.dequeueReusableCell(withIdentifier: "chat_room_cell", for: indexPath) as! PrivateChatUITableViewCell
let indexedID = chatsIndex[indexPath.row]
cell.ContactName.text = chatsDictionary[indexedID]?.GetContactName()
cell.ContactID = chatsDictionary[indexedID]?.GetContactID()
return cell
}
And in my PrivateChatUITableViewCell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = ChatsTableView.dequeueReusableCell(withIdentifier: "chat_room_cell", for: indexPath) as! PrivateChatUITableViewCell
//cell.ContactImageView = UIImageView.loadImageUsingUrlString(contactImg)
let indexedID = chatsIndex[indexPath.row]
cell.ContactName.text = chatsDictionary[indexedID]?.GetContactName()
cell.ContactID = chatsDictionary[indexedID]?.GetContactID()
//cell.PopulateCell()
return cell
}
public func PopulateCell()
{
let currentID = Constants.refs.currentUserInformation?.uid
Constants.refs.databaseChatsLite.child(currentID!).child(ContactID!).observeSingleEvent(of: .value, with: {(snapshot) in ...})
}
The code crashes when it reaches the Constants.refs.databaseChatsLite.child(currentID!).child(ContactID!)
line because ContactID isn't initialized.
This is being called when casting cell to PrivateChatUITableViewCell
I haven't changed my code and this used to work, so I am not sure what changed or what I am doing wrong. Where should my code be fixed?

Fetching from Core Data and display in UITableView with custom cell

I have a UITableView with a custom cell:
title, label, text
These are 3 elements of UITextView, now I have an entity in my core data:
I want to put title, in title, the date in label and introText in text:
I did this:
do{
var request = NSFetchRequest<NSFetchRequestResult>(entityName: "Actualites")
let count = try context.count(for: request)
if (count == 0) {
REST().SaveArticles(limit: 5, limitstart: 0, catid: 6, key: "xxx", context: context)
} else {
var actualites = [Actualites]()
actualites = try context.fetch(request) as! [Actualites]
let cell:ActuTblCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! ActuTblCell
for actualites in actualites {
print(actualites.title)
}
}
}catch{
print(error)
}
I can get the titles in the loop, but how to display the data ? Do I have to create 3 arrays ?
EDIT:
I think I have to do a loop here ?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ActuTblCell
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy HH:mm"
cell.titleActuCell.text = actualites[indexPath.row].title
cell.dateActuCell.text = formatter.string(from: actualites[indexPath.row].created! as Date)
cell.descriptionActuCell.text = actualites[indexPath.row].introText
return cell
}
Thread 1: Fatal error: Index out of range
In your view controller keep an array of Actualites: var actualites = [Actualites](). Then your else block would look like this:
else {
actualites = try context.fetch(request) as! [Actualites]
tableview.reloadData()
}
You should implement the UITableViewDataSource protocol to return the number of cells based on the actualites array, and in the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) you get the actuality for every cell by this statement: let actuality = actualites[indexPath.row] and display in the appropriate cell.

reloading table view when search bar is empty

I am new in swift.I have implement the search operation for json show in table view about description field .
func updateSearchResults(for searchController: UISearchController) {
// If we haven't typed anything into the search bar then do not filter the results
if searchController.searchBar.text! == "" {
filteredsneakernews = [classObject.descriptionn]
self.results = self.placeHolderArray
self.DiscoveryNewsTableView.reloadData()
} else {
// Filter the results
//filteredsneakernews = [classObject.descriptionn].filter { $0.description.lowercased().contains(searchController.searchBar.text!.lowercased()) }
results = results.filter {
$0.description.lowercased().contains(searchController.searchBar.text!.lowercased()) }
// self.results = self.placeHolderArray
self.DiscoveryNewsTableView.reloadData()
}
// self.DiscoveryNewsTableView.reloadData()
}
Here is code for table view
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell
classObject.getDataForTableView(results: results, index: indexPath.row)
//let image_url = filteredsneakernews[indexPath.row].image
// cell.sneakerImageView.image=filteredsneakernews[indexPath.row].image
self.placeHolderArray = self.results
cell.newsTitle.text = classObject.descriptionn
let imageURLPathString = newsurl + classObject.image
let url1 = URL(string: imageURLPathString)
print("xyz", url1)
let data = try? Data(contentsOf: url1!)
if let imageData = data {
let image = UIImage(data: imageData)
cell.sneakerImageView.image = image
}
return cell
}
here is the class that i have made for getting data from json
class getData: NSObject {
var descriptionn : String = ""
var image : String = ""
// static let shared = getData()
func getDataForTableView(results: [[String:String]], index : Int){
var productArray = [String:String]()
productArray = results[index]
descriptionn = productArray["description"]!
image = productArray["images"]!
}
}
The search bar searching the result. when i finish the search when search bar is empty i want table view should reload the data .it should show the all record in table view when search bar is empty .but it is not reloading table view when search bar is empty .you can download the code from this link. https://drive.google.com/file/d/1G3QUYLgLDwIjNKb-HB-zO98l14HrcRVe/view?usp=sharing
#ajadka I have seen your code and there is small mistake ...just replace this line n it'll work correctly ..
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "discoveryNewscell") as! DiscoveryNewsTableViewCell
// self.placeHolderArray = self.results comment this line here
...... }
and put that line here
func single_news(userid: Int) {
.......
self.results = jsonValue.object(forKey: "data") as! [[String:String]]
self.placeHolderArray = self.results //put here that line
..........
}

TableView Data Not Reloading Swift

I am working on restaurant app where i need to get all restaurant type..i successfully get all data but tableview not reloading..
var arrSubMenu = [ResataurantType]()
//TableView Datasource And Delegate Method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(arrSubMenu.count)
return arrSubMenu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: leftMenuTableViewCell =
tableView.dequeueReusableCell(withIdentifier: "tableCell") as!
leftMenuTableViewCell
cell.name.text = self.arrSubMenu[indexPath.row].type
return cell
}
func getRestaurantType() {
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFJSONRequestSerializer()
manager.get(RESTAURANTTYPE, parameters: nil, progress: nil, success: {
(operation, responseObj) in
if let objDic = responseObj as? [String:Any] {
if let objArray = objDic["RESTAURANT_TYPE"] as? NSArray {
for objType in objArray {
let ObjRestaurant = ResataurantType()
if let objString = objType as? String {
ObjRestaurant.type = objString
}
self.arrSubMenu.append(ObjRestaurant)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}) { (operation, error) in
print(error)
}
}
I call this function in ViewDidLoad() but still i can't polulate tableview with record
-These can be possible reason from my person experience
TableView's dataSource don't set to self.
-Verification :- Break point on tableView Data Source & Delegate methods.
your arrSubMenu array don't contain the single value.
-Verification:- Break point & print the arrSubMenu before reloading the tableView.
You have just to enter:
First a IBOutlet:
#IBOutlet var tableView : UITableView
In viewDidLoad:
tableView.dataSource = self //OR connection between tableView in storyboard and tableView in swift class
When are you calling getRestaurantType() ? Could it be that it is called before the tableview's datasource is assigned ? That could make the tableview appear empty although the underlying data is present. And, unless you call reloadData() at some other point in the program, it will not refresh itself.
Replace below at cell for row at index method
let cell =
tableView.dequeueReusableCell(withIdentifier: "tableCell" ,for: indexPath)as!
leftMenuTableViewCellenter

How do I get the value from the model to the controller

This is my first program using MVC design pattern, I'm stuck how to get the values from the model to my controller and to display it in my view. I'll show you what I have done. Kindly clarify me what I did wrong? Or show me how it can be done in other way around.
Model
class songData: NSObject {
var artistName: String
var albumName: String
init(artistName: String, albumName: String) {
self.artistName = artistName
self.albumName = albumName
}
}
Controller
#IBAction func doTheSearch(sender: AnyObject) {
itunesAPI().itunesSearch({(song : songData) in
})
self.tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return song1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
var artistAndAlbum = itunesAPI().array[indexPath.row]
cell.textLabel?.text =
cell.detailTextLabel?.text =
return cell
}
API
func itunesSearch(completionHandler:(songData)->()) {
Alamofire.request(.GET, "http://itunes.apple.com/search?", parameters: ["term" : "tamil new songs", "media" : "music"])
.responseJSON { (response) in
let json = JSON(response.result.value!)
if let jsonData = json["results"].arrayObject {
self.array = jsonData as! [[String : AnyObject]]
if self.array.count > 0 {
// self.array = jsonData as! [[String : AnyObject]]
// if let resultsDict = resultsArray.first {
let albumName = json["results"]["collectionName"].stringValue
let artistName = json["results"]["artistName"].stringValue
let song = songData(artistName: artistName, albumName: albumName)
completionHandler(song)
}
}
I do have the nothing on my view except the story board which consists of a table view with a single cell. I need to get the response from the API and show it in the view.
First, you're going to want to reload your table after the data is returned. Update your IBAction to this:
itunesAPI().itunesSearch({(song : songData) in
self.tableView.reloadData()
})
Otherwise reloadData will get called before the data is returned. Set a property on the viewController to house the data. Also, it's good practice to start a class name with a capital letter.
var tableData:[SongData] = [SongData]()
Then set this variable when the data successfully returns:
itunesAPI().itunesSearch({(song : songData) in
self.tableData.append(song) // add the result to the list of data
self.tableView.reloadData() // reload the table
})
Then set the cells as so:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
var artistAndAlbum = self.tableData[indexPath.row]
cell.textLabel?.text = artistAndAlbum.artistName
cell.detailTextLabel?.text = artistAndAlbum.albumName
return cell
}