Querying parse for objects with a Pointer, swift - swift

I'm trying to make a Query with a Pointer in Parse. I have two classes "Discover" and "DiscoveryDetails". I want to get the discovery details of an object that's picked from the discovery class.
Discovery Class
DiscoveryDetails Class - with the discoverID as the pointer.
The discovery objects are displayed in a DiscoveryTableView and on selecting one of the items, I want to query the objects of with an ID related to that selection in a DiscoveryDetailsTableView.
The DiscoveryTableView shows the objects as they appear in the class but the DiscoveryDetailsTableView shows all the objects instead of those related to the Cell I selected.
This is my didSelectRowAtIndexPath Code in the DiscoveryTableView:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let mainStoryboard = UIStoryboard(name: "Discovery", bundle: nil)
let discoveryDetailView = mainStoryboard.instantiateViewControllerWithIdentifier("discoveryDetailTVC") as! DiscoveryDetailTableViewController
let object = self.objectAtIndexPath(indexPath)
discoveryDetailView.titleString = object?.objectForKey("workoutName") as! String
discoveryDetailView.describtionString = object?.objectForKey("workoutDetails") as! String
discoveryDetailView.numberOfWorkouts = object?.objectForKey("numberOfWorkouts") as! Int
discoveryDetailView.imageFile1 = object?.objectForKey("image1") as! PFFile
discoveryDetailView.imageFile2 = object?.objectForKey("image2") as! PFFile
discoveryDetailView.imageFile3 = object?.objectForKey("image3") as! PFFile
let row = indexPath.row //we know that sender is an NSIndexPath here.
let selectedObj = objects![row] // some var where you hold your data
discoveryDetailView.varInDDT = selectedObj
self.navigationController?.pushViewController(discoveryDetailView, animated: true)
}
In my DiscoveryDetailsTableView I have this code:
var titleString: String!
var describtionString: String!
var numberOfWorkouts: Int!
var imageFile1: PFFile!
var imageFile2: PFFile!
var imageFile3: PFFile!
var varInDDT : PFObject?
//MARK: Query for Table with the details
override func queryForTable() -> PFQuery {
let discoveryQuery = PFQuery(className: "DiscoveryDetails")
discoveryQuery.cachePolicy = .CacheElseNetwork
discoveryQuery.whereKey("discoveryID", equalTo: PFObject(withoutDataWithClassName: "Discovery", objectId: "\(varInDDT!.objectId!)"))
discoveryQuery.orderByDescending("createdAt")
return discoveryQuery
}
override func viewDidLoad() {
super.viewDidLoad()
//Header Display
let imagesArray = [imageFile1, imageFile2, imageFile3]
let imagePicked = randomIntergerInRange(0, high: imagesArray.count)
titleLabel.text = titleString.uppercaseString
self.subtitleLabel.text = describtionString
self.numberOfWorkoutsLabel.text = "\(numberOfWorkouts!) Workouts"
//Pick a random Image from the Images
imagesArray[imagePicked].getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil
{
if let imageData = imageData
{
let image = UIImage(data:imageData)
self.backgroundImage.image = image
}
}
})
...
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var discoveryDetailItemsCell:DiscoveryDetailTableViewCell! = tableView.dequeueReusableCellWithIdentifier("DiscoveryDetailTableViewCell") as? DiscoveryDetailTableViewCell
...
discoveryDetailItemsCell.titleLabel.text = object?.objectForKey("exerciseName") as? String
discoveryDetailItemsCell.titleLabel.textColor = UIColor.whiteColor()
discoveryDetailItemsCell.durationAndSetsLabel.text = "\((object?.objectForKey("durationOrSets"))!)"
discoveryDetailItemsCell.minAndSetLabel.text = "mins"
...
return discoveryDetailItemsCell
}
There may be similar questions out there but I have not found anything that answers this or I am probably not seeing my mistake clearly.
Thanks for the help in advance. :)

for query with pointer U have to use query like that
let discoveryQuery = PFQuery(className: "DiscoveryDetails")
discoveryQuery.cachePolicy = .CacheElseNetwork
discoveryQuery.whereKey("discoveryID", equalTo: PFObject(withoutDataWithClassName: "Discovery", objectId: "\(varInDDT!.objectId!)"))
discoveryQuery.orderByDescending("createdAt")
return discoveryQuery
for downloading the detail you have to pass at least ID of the object you want to download from the first viewController to the second or you can pass the whole PFObject
DiscoveryTableView
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showDetail", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showDetail"){ // define the segue Name
let controller = (segue.destinationViewController as! DiscoveryDetailTableViewController)
let row = sender!.row //we know that sender is an NSIndexPath here.
let selectedObj = discoveryObjects[row] // some var where you hold your data
controller.varInDDT = selectedObj
}
}
and define the var of PFObject in detailVC
DiscoveryDetailTableViewController
var varInDDT : PFObject?

Related

Data is not displayed in TableView from Firebase

I have a 2 problems with displaying data in a table from Firebase.
Nothing displayed in TableView from Firebase
I I can not add a link(child) to a variable
Print is working. I get access to Firebase, but nothing is added to TableView. Please, look at my code and correct where i'm wrong.
It's my model
class Exercises {
var titleExercise = ""
var descriptionExercise = ""
init (titleExercise: String, descriptionExercise: String) {
self.titleExercise = titleExercise
self.descriptionExercise = descriptionExercise
}
}
It's my ViewController
class ExercisesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: Properties
var refWorkout: String = ""
var workout: TrainingProgram?
var ref: DatabaseReference!
#IBOutlet weak var tableView: UITableView!
var exercises = [Exercises]()
//MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
fetchExercises()
tableView.dataSource = self
tableView.delegate = self
refWorkout = workout!.title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return exercises.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ExercisesTableViewCell
let workouts = exercises[indexPath.item]
cell.titleLabel.text = workouts.titleExercise
cell.descriptionLabel.text = workouts.descriptionExercise
return cell
}
func fetchExercises() {
Database.database().reference().child("programs").child("OPEN SPACE").child("exercises").observe(.childAdded) { (snapshot) in
print(snapshot.value)
if let dict = snapshot.value as? [String: AnyObject] {
let newTitle = dict["title"] as! String
let newDescription = dict["description"] as! String
let exerciseTableCell = Exercises(titleExercise: newTitle, descriptionExercise: newDescription)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
And I have second question. It also addresses this issue.
As you can see, I have refWorkout = workout!.title Here comes the title from previous ViewController , and refWorkout is a child for Firebase. If I will write next code
ref = Database.database().reference().child("programs").child(refWorkout).child("exercises")
ref.observe(.childAdded) { (snapshot) in
print(snapshot.value)
}
Everything will work. Print will work. But if I insert this code to func fetchExercises() - > It will look like
func fetchExercises() {
Database.database().reference().child("programs").child(refWorkout).child("exercises").observe(.childAdded)...
My app crashed.
Please help me with two questions. Thank you!
My Firebase structure
This is a common mistake, you are reloading the table view too soon and you don't assign/append the result to the data source array
The observe API works asynchronously, put the line to reload the table view into the closure
func fetchExercises() {
Database.database().reference().child("programs").child("OPEN SPACE").child("exercises").observe(.childAdded) { (snapshot) in
print(snapshot.value)
if let dict = snapshot.value as? [String: Any] { // most likely all values are value type
let newTitle = dict["title"] as! String
let newDescription = dict["description"] as! String
let exercise = Exercises(titleExercise: newTitle, descriptionExercise: newDescription)
self.exercises.append(exercise)
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
Side note:
You class contains 3 bad practices:
Semantically objects used in collection types should be named in singular form.
Don't declare properties with default values if there is an initializer.
There is too much redundant information in the variable names
And in most cases a struct and even constants are sufficient. I'd recommend
struct Exercise {
let title : String
let description : String
}
In a struct you get the initializer for free.

populate UITableView with data stored in Firebase database

I have a UITableVIew in my iPhone application that populates each cell using an array but the question is how do you populate the array with values retrieved from the firebase database:
func retData(){
rootRef.child("users").child("Test").observeEventType(.Value){
(snap: FIRDataSnapshot) in
}
}
var no1 = ["3","6","3","4","5","20","34","34"]
Table Code:
func tableView(tableView: UITableView, cellForRowAtIndexPath
indexPath: NSIndexPath) -> UITableViewCell {
let cell1 = self.h_table.dequeueReusableCellWithIdentifier("cell1",
forIndexPath: indexPath) as! Hole_Cell
cell1.s_label.text = usersArray[indexPath.row]
firebase data Structure:
--Users
--Test: 1
--Test1: 2
--Test2: 3
--Test4: 4
Try this:
var usersArray: [String]?
func retData() {
rootRef.child("users").observeEventType(.Value, withBlock: { snapshot in
usersArray = [String]()
for user in snapshot.allObjects as! [FIRDataSnapshot] {
let userString = user.value as? String
usersArray?.append(userString!)
}
})
}
***Edit Try this:
var usersArray = [String]()
func retData() {
rootRef.child("users").observeEventType(.Value, withBlock: { snapshot in
let usersDict = snapshot.value as! [String:String]
self.usersArray= Array(usersDict.values)
self.tableView.reloadData()
}
})
}
*** Again Edit: Add this within the closure to account for when users has no data.
if let _ = snapshot.value as? NSNull {
return
} else {
let usersDict = snapshot.value as! [String:String]
self.usersArray= Array(usersDict.values)
self.tableView.reloadData()
}
Check my latest Questions, basically the same stuff. Checkout Firebase UI, very useful.
I used a ViewController with a table view and a Prototype Cell in it. Then this worked for me:
import Firebase
import FirebaseDatabaseUI
class LinksViewController: UIViewController, UITableViewDelegate {
var dataSource: FirebaseTableViewDataSource?
var ref = FIRDatabase.database().reference()
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
dataSource = FirebaseTableViewDataSource.init(query: myQuery(),prototypeReuseIdentifier: "<Your-Identifier>", view: self.tableView)
dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
//Populate your Cell here
}
tableView.dataSource = dataSource
tableView.delegate = self
}
}
Note that the myQuery is basically then your first line.

How can I transfer an image from table cell to newviewcontroller using prepare for segue?

How can I transfer an image from table cell to the Newviewcontroller using prepare for segue? I was able to transfer the label data but not the image. I am using parse.com as my backend to retrieve the image. thanks
import UIKit
class mainVC: UIViewController, UITableViewDataSource, UITableViewDelegate, {
#IBOutlet weak var resultsTable: UITableView!
var resultsStartdateArray = [String]()
var resultsTweetImageFiles = [PFFile?]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsTweetImageFiles.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 350
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:mainCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! mainCell
cell.dateLbl.text = self.resultsStartdateArray[indexPath.row]
resultsTweetImageFiles[indexPath.row]?.getDataInBackgroundWithBlock({
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.tweetImg.image = image
}
})
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let upcoming: NewViewController = segue.destinationViewController as! NewViewController
let indexPath = self.resultsTable.indexPathForSelectedRow!
let titleString = self.resultsStartdateArray[indexPath.row] as String
let imageTitle = self.resultsTweetImageFiles[indexPath.row] as PFFile?// i have tried this but it didnt work
upcoming.imageTitle == imageTitle // << not working
upcoming.titleString = titleString
self.resultsTable.deselectRowAtIndexPath(indexPath, animated: true)
}
import UIKit
class NewViewController: UIViewController {
#IBOutlet weak var dateLbl: UILabel!
#IBOutlet weak var tweetImage: UIImageView!
var titleString: String!
var imageTitle: UIImage!
override func viewDidLoad()
{
super.viewDidLoad()
self.dateLbl.text = self.titleString
self.tweetImage.image = self.imageTitle
}
In this line of code you create imageTitle as PFFile object:
let imageTitle = self.resultsTweetImageFiles[indexPath.row] as PFFile?
And then you try set it to UIImage reference:
upcoming.imageTitle == imageTitle
But imageTitle from NewViewController expects the image with UIImage type and not some incomprehensible for it object like PFFile
That's why it does not work.
To fix it you need to convert data from your PFFile object to UIImage and only then transmit it to your NewViewController object. You did not write the form in which the data contained in your PFFile object so assume that it NSData format for example. In this case you can do something like this:
if let imageObject = self.resultsTweetImageFiles[indexPath.row] as? PFFile {
if let imageData = imageObject.getData as? NSData {
if let image = UIImage(data: imageData) {
upcoming.imageTitle = image
}
}
}
Or if you have the some String object that contain your image in base64 format you can first convert it to NSData object like this:
let imageData = NSData(base64EncodedString: imageString, options: .IgnoreUnknownCharacters)

Tutorial in retrieving, mutating and saving array from Parse.com in Swift with UITableView

import UIKit
class FeedTableViewController: UITableViewController {
var navBar:UINavigationBar=UINavigationBar()
let font = UIFont(name: "Baskerville", size: 15)
var feedData:NSMutableArray = NSMutableArray()
required init(coder aDecoder: NSCoder){
super.init(coder: aDecoder)
}
#IBAction func likeButton(sender: AnyObject) {
if var votes:Int? = quote!.objectForKey("votes") as? Int {
votes!++
}
}
#IBAction func loadData(sender: AnyObject?) {
feedData.removeAllObjects()
var findFeedData:PFQuery = PFQuery(className: "userQuotes")
findFeedData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]?, error:NSError?)->Void in
if error == nil{
if let objs = objects{
for object in objs{
let quote:PFObject = object as! PFObject
self.feedData.addObject(quote)
// let user:PFUser = (object as! NSArray).lastObject as! PFUser
}
//println(self.feedData)
let array:NSArray = self.feedData.reverseObjectEnumerator().allObjects
self.feedData = NSMutableArray(array: array)
NSOperationQueue.mainQueue().addOperationWithBlock({
self.tableView.reloadData()
})
}
}
}
}
override func viewDidAppear(animated: Bool) {
self.loadData( nil )
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Quotezilla"
// 3
//self.navigationItem.setRightBarButtonItem(rightSearchBarButtonItem, animated: true)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
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 Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return feedData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:QuoteTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! QuoteTableViewCell
let quote:PFObject = self.feedData.objectAtIndex(indexPath.row) as! PFObject
cell.contentTextView!.font = font
cell.timeStampLabel!.font = font
cell.publisherLabel!.font = font
cell.contentTextView.alpha = 0
cell.timeStampLabel.alpha = 0
cell.publisherLabel.alpha = 0
cell.contentTextView.text = quote.objectForKey("content") as! String
//cell.publisherLabel.text = quote.objectForKey("publisher") as? String
/* func loadLikes(){
if var votes:Int? = quote.objectForKey("votes") as? Int {
votes!++
}
}*/
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
cell.timeStampLabel.text = dateFormatter.stringFromDate(quote.createdAt!)
var votes:Int? = quote["votes"] as? Int
if votes == nil {
votes = 0
}
cell.likesLabel?.text = "\(votes!)"
var myObject = quote["publisher"] as? PFObject
myObject?.fetchIfNeeded()
if let foundUser = myObject as? PFUser{
cell.publisherLabel.text = foundUser.username
UIView.animateWithDuration(0.7, animations: {
cell.contentTextView.alpha = 1
cell.timeStampLabel.alpha = 1
cell.publisherLabel.alpha = 1
})
}
return cell
}
So what I am essentially attempting to do is create a likes or votes button. As you see in the code I have a likeButton action that is supposed to auto-increment the likes section in parse. I display the current likes that I have filled into the rows in Parse itself in the cellForRowAtIndexPath function. The problem is that I cannot call quote.objectForKey("votes"), because I initialize it later. I have been poring over this problem and cannot find a way to make the votes update in parse through the likeButton action.
You must live with life on the network. That means your table won't have certain data available when the App starts. Handle a missing object or missing key within a particular cell gracefully and just use some kind of placeholder value. When the parse callback executes, you are already correctly forcing a refresh.
OK So BIG EDIT
This class needed a lot of work. I'm not even going to spell out every change here, but it's basically a complete Parse.com tutorial at this point.
This code compiles cleanly but I can't be sure of everything in your context. In particular do you have a 'likesButton' on every table row as part of your custom table cell view? I'm assuming that.
class FeedTableViewController: UITableViewController {
var navBar = UINavigationBar()
let font = UIFont(name: "Baskerville", size: 15)
var feedData = [PFObject]()
static let cellID = "cell"
// NOTE! See how this tag is set below
#IBAction func likeButton(sender: UIButton) {
let quote = feedData[sender.tag]
if let votes = quote.objectForKey("votes") as? Int {
quote.setObject(votes + 1, forKey: "votes")
}
else {
// CHALLENGE FOR YOU: handle the case of no votes attribute
}
// UPDATE the local UI
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: sender.tag, inSection: 0)],
withRowAnimation: .None)
// CHALLENGE FOR YOU: UPDATE Parse...start a new question if necessary
}
#IBAction func loadData(sender: AnyObject?) {
feedData.removeAll()
PFQuery(className: "userQuotes").findObjectsInBackgroundWithBlock {
[unowned self]
(objects: [AnyObject]?, error: NSError?) -> Void in
if let objs = objects {
for object in objs {
self.feedData.append(object as! PFObject)
}
self.feedData = self.feedData.reverse()
}
NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.reloadData() }
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadData(nil)
self.title = "Quotezilla"
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(FeedTableViewController.cellID, forIndexPath: indexPath) as! QuoteTableViewCell
cell.likesButton!.tag = indexPath.row // See how tag works with the above
cell.contentTextView!.font = font
cell.timeStampLabel!.font = font
cell.publisherLabel!.font = font
cell.contentTextView.alpha = 0.0
cell.timeStampLabel.alpha = 0.0
cell.publisherLabel.alpha = 0.0
let q = feedData[indexPath.row]
if let content = q.objectForKey("content") as? String {
cell.contentTextView.text = content
}
else {
cell.contentTextView.text = "Content not found!"
}
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
cell.timeStampLabel.text = dateFormatter.stringFromDate(q.createdAt!)
let votes = (q.objectForKey("votes") as? Int) ?? 0
cell.likesLabel?.text = "\(votes)"
let myObject = q.objectForKey("publisher") as? PFObject
myObject?.fetchInBackgroundWithBlock {
[unowned self]
(object: PFObject?, error: NSError?) in
NSOperationQueue.mainQueue().addOperationWithBlock {
if let foundUser = object as? PFUser {
cell.publisherLabel.text = foundUser.username
UIView.animateWithDuration(0.7) {
cell.contentTextView.alpha = 1.0
cell.timeStampLabel.alpha = 1.0
cell.publisherLabel.alpha = 1.0
}
}
else {
cell.publisherLabel.text = "Publisher not found!"
}
}
}
return cell
}
}

prepare for segue.. from UITableView to DetailView with parse Objects

trying to get from my UITableViewController to the detail view controller with these PFObjects...thanks in advance!
error i can't seem to reconcile..."Cannot subscript a value of type 'String' with an index of type 'String'"
I want the queried objects to present on the detail view controller...
here is my query and my prepare for segue...i can't seem to access the objects in the prepare for segue...
var customerName = [String]()
var customerAddress = [String]()
var query = Pfuser.query
query.whereKey("userId",equalTo:adminFollowingUser)
query.findObjectsInBackgroundWithBlock({ (adminObjects, error) -> Void in
if let objects = adminObjects {
for object in objects {
self.customerName.append(object["customerName"] as! String)
self.customerAddress.append(object["customerStreetAddress"] as! String)
// Here is the prepare for segue....
override func prepareForSegue(segue: UIStoryboardSegue, sender:
AnyObject?)
{
if (segue.identifier == "thesePools")
{
let employeeDetailVC: EmployeeDetailViewController = segue.destinationViewController
as! EmployeeDetailViewController
// indexPath is set to the path that was tapped
let indexPath = self.tableView.indexPathForSelectedRow
let customerNameLabel = self.customerName[indexPath!.row]
let customerAddressLabel = self.customerAddress[indexPath!.row]
employeeDetailVC.customerString = customerNameLabel
employeeDetailVC.addressString = customerAddressLabel
here is my detail view controller receiving the Strings.
//DetailViewController
var customerString = String()
var addressString = String()
override func viewDidLoad() {
super.viewDidLoad()
self.customerLabel.text = customerString
self.addressLabel.text = addressString
var currentObject = String() is a string and you set it to a string in the prepareForSegue.This should do the trick:
self.customerTextField.text = curentObject
And remove all the other stuff.
Try that
let nav = segue.destinationViewController as! CustomerDetailViewController
var indexPath :NSIndexPath = self.tableview.indexPathForSelectedRow()!
var object = self.CustomerName[indexPath.row] as! String
nav.currentobject = object
I would recommend using a PFQueryTableViewController.
This is a UI object that is provided by Parse and loads data from your class 50x faster.
Here is an example of how to create it:
import UIKit
class YourTableViewController: PFQueryTableViewController {
// Initialise the PFQueryTable tableview
override init!(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Configure the PFQueryTableView
self.parseClassName = "yourClass"
self.textKey = "yourObject"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery! {
var query = PFQuery(className: "yourClass")
query.orderByAscending("yourObject")
return query
}
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as CustomTableViewCell!
if cell == nil {
cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
// Extract values from the PFObject to display in the table cell
cell.info.text = object["info"] as String
// Date for cell subtitle
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateForText = object["date"] as NSDate
cell.date.text = dateFormatter.stringFromDate(dateForText)
return cell
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var detailScene = segue.destinationViewController as YourDetailViewController
// Pass the selected object to the destination view controller.
if let indexPath = self.tableView.indexPathForSelectedRow() {
let row = Int(indexPath.row)
detailScene.currentObject = objects[row] as? PFObject
}
}
At the end make sure to also created a custom cell class.