loading data into TableView from Parse - swift

Hi Guys I have created a function which is below which saves items to a tweetData : [PFObject] array
func loadData() {
//all current data to be displayed, adding data 1 by 1 remove whats there on reloading
tweetData.removeAll()
//query database for all tweets, very important that whats in the classname here, is the
//same name as the class with Parse where these are being stored
let findTweets:PFQuery = PFQuery(className: "Tweets")
findTweets.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
for object:PFObject in objects! {
self.tweetData.append(object)
}
//--very important!!! dont forget to reload table data otherwise you will return no results
self.tableView.reloadData()
} else {
print("nothing to load")
}
}
}
how can I get this into my tableview to display the data? been struggling and getting a variety of errors. This is my table view cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
//use your custom table view cell here which is defined in another class
let cell:CellTableViewCellController = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CellTableViewCellController
//NEED TO LOAD MY DATA
return cell
//-----add load data function to viewDidAppear method
}
could anyone help me on this at all? thanks

all sorted just used query.objectforkey
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//use your custom table view cell here which is defined in another class
let cell:CellTableViewCellController = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellTableViewCellController
let query = tweetData[indexPath.row]
cell.textLabel!.text = query.objectForKey("TweetContent") as? String
return cell
//-----add load data function to viewDidAppear method
}

Related

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 let my TodayWidget read out of CoreData in Swift?

So I'm making this app in which the user can store data in CoreData and see it in a table view.
This works like it should, but now I want the data to been seen in a table view, which is located in a today widget.
I already tried to do this the "regular way" by trying to fetch, but the widget isn't able to read it via the AppDelegate file.
The error that I get says the following : " 'shared' is unavailable: Use view controller based solutions where appropriate instead."
I also get the error : "Use of undeclared type 'AppDelegate'"
Is anyone capable in helping me?
Thanks,
EDIT :
This is the code I use to fetch the data in the ViewController :
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSManagedObject>(entityName: "ToDoList")
do {
toDoItems = try managedContext.fetch(request)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
toDoTableView.tableFooterView = UIView()
self.toDoTableView.reloadData()
toDoTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let cell = UITableViewCell()
cell.contentView.backgroundColor = UIColor.clear
cell.backgroundColor = UIColor.clear
toDoTableView.backgroundColor = UIColor.clear
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return toDoItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let activities = toDoItems[indexPath.row]
let cell = toDoTableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text =
activities.value(forKeyPath: "todoitems") as? String
return cell
}
}
Please note that this is not my entire code, but some fragments which all together create the fetch function

How to populate data from class model to tableview

My data is coming in modal class named Menu by creating its object menus. Now How can i send the menu names to tableview to show in particular cell
var menus = [Menu]()
for (_, content) in json {
let menu = Menu(id: Int(content["id"].stringValue),
name: content["name"].string,
image: content["image"].string,
coupon: content["coupon"].int,
icon: content["icon"].string,
order: Int(content["order"].stringValue),
aname: content["name"].string,
options: Int(content["options"].stringValue),
subcategory:content["subcategory"].arrayObject)
menus.append(menu)
}
for menu in menus {
print(menu.name)
print(menu.id)
print(menu.subcategory)
}
print(menus.count)
Here All the data is saved in Menu class by the help of menus object.I have added the codes to show data to tableview. here i have created custom tableview and trying to populate it
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menus.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Menucell", forIndexPath: indexPath)as! MENUTableViewCell
cell.Ordermenu.text = (" \(menus[indexPath.row])")///here its not fetching the value
return cell
}
Its not working . how the implementation should be ?
It shows the projectName.classname
updated after accepting answer
Try below line of code. Hope it will help you...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Menucell", forIndexPath: indexPath)as! MENUTableViewCell
let menu : Menu = menus[indexPath.row]
cell.Ordermenu!.text = menu. name
return cell
}
Do you register the table cells? Try something like this...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell: MENUTableViewCell! = tableView.dequeueReusableCellWithIdentifier("MENUTableViewCellIDENTIFIER") as? MENUTableViewCell
if cell == nil
{
let nib: UINib = UINib(nibName:"MENUTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier:"MENUTableViewCellIDENTIFIER")
cell = tableView.dequeueReusableCellWithIdentifier("MENUTableViewCellIDENTIFIER") as! CompactIncidentCellView
//cell.selectionStyle = UITableViewCellSelectionStyle.None
}
// work with cell here...
cell.Ordermenu.text = (" \(menus[indexPath.row])")
return cell
}

Only one custom tableviewcell working correctly

I created a custom tableviewcell with a photo and two labels. I queried some data from parse and the cells are suppposed to update the image and labels to reflect the query, however only the first viewcell works correctly. The image and labels work, however the second viewcell only displays the image correctly, the uilabels do not display any text. I've looked over the code multiple times and cant seem to figure out what i am doing wrong...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("mySpotCell")/*, forIndexPath: indexPath)*/as? CustomTableViewCell
// cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
if let value = mySpots[indexPath.row]["location"] {
let location = CLLocation(latitude: (value.latitude)!, longitude: (value.longitude)!)
self.geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemark, error) -> Void in
if error != nil {
print("error: \(error!.localizedDescription)")
}
if let pm: CLPlacemark = placemark![indexPath.row] {
// var pm = placemark![indexPath.row] as CLPlacemark
//self.parkingSpotAddress.text = pm.thoroughfare
// self.navigationController?.navigationBar.topItem?.title = pm.thoroughfare
//cell!.textLabel?.text = "\(pm.subThoroughfare!) \(pm.thoroughfare!)"
cell?.subtitleLabel.text = "\(pm.subThoroughfare!) \(pm.thoroughfare!)"
cell?.titleLabel.text = pm.description
print(cell?.subtitleLabel.text)
print(cell?.titleLabel.text)
}
})
if let parkingSpotImageFile: PFFile = mySpots[indexPath.row]["firstPhoto"] as! PFFile! {
parkingSpotImageFile.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil {
cell?.spotImageView.image = UIImage(data: imageData!)
// self.imageIndicator.stopAnimating()
// self.imageIndicator.hidden = true
}
})
}
I think you can check your func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int first. The value you return inside is the number of row it will show and load in tableview.
And my cellForRowAtIndex is like this, I think yours should be alright also. Just check the number of row in section.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MenuTableViewCell = tbvMenu.dequeueReusableCellWithIdentifier("identifier") as! MenuTableViewCell
let temp:String = MenuArr[indexPath.row] as! String
cell.mainMenuTitle.text = temp
return cell
}

How I can show only certain cells taken from Dictionary in a tableView in Swift

I am using a dictionary in order to fill a tableview.
Trying to appear only cells that have a certain userID, but it return also the cells that doesn't have this userID.
I have managed to count only the items from dictionary with the certain userID and if for example my dictionary has 8 entries and I need to show only the last 2 entries which have different userID, it returns 2 empty cells (which are the first 2 in the dictionary.
How I can get only the cells with the certain userID?
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
var returnCount:Int = 0
let currentUserId = NSUserDefaults.standardUserDefaults().stringForKey("userId")
for place in places {
if place["userID"] == currentUserId {
returnCount++
}
}
return returnCount
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let currentUserId = NSUserDefaults.standardUserDefaults().stringForKey("userId")
let currentPlacesUserId = places[indexPath.row]["userID"]
if currentPlacesUserId == currentUserId {
cell.textLabel!.text = places[indexPath.row]["name"]
cell.detailTextLabel?.text = places[indexPath.row]["issue"]
}
return cell
}
The fact is that you should not do this kind of logic inside de tableView delegate methods. Try getting the places from that userId when you load this array.
If you really want to proceed with the approach you are currently using try the following:
Not sure if this gonna work, but you are creating the cell even if it doesnt have the user Id you want. Try this:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let currentUserId = NSUserDefaults.standardUserDefaults().stringForKey("userId")
let currentPlacesUserId = places[indexPath.row]["userID"]
if currentPlacesUserId == currentUserId {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel!.text = places[indexPath.row]["name"]
cell.detailTextLabel?.text = places[indexPath.row]["issue"]
return cell
} else{
return nil
}
}