How to create a PFQueryTableViewController with Parse in Swift? - ios

I've imported all the frameworks required but from that point on I don't quite know what to do (I'm new to Swift and no absolutly nothing about Objective C). Parse docs aren't in Swift yet so can someone please provide me with a starting point?
I've initialized my view controller (which doesn't appear when I run the app, I just get a black screen; but based on this video, I should see a table: https://parse.com/tutorials/parse-query-table)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Link to Parse
Parse.setApplicationId("...", clientKey: "...")
var controller:PFQueryTableViewController = PFQueryTableViewController(className: "test1")
self.window?.rootViewController = controller
self.window?.makeKeyAndVisible()
return true

Make sure you have imported all the parse SDK's
Create a
2 new cocoa touch class', give one the subclass of PFQueryTableViewController and the other PFTableViewCell. Hook them up in the storyboards. Make sure the Tableview and the cell are pointing to these files. Your Tableview file should look something like this;
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
}
}
Make sure you have set the cells reuse identifier to match what you are setting it to in this code.
When you I called cell.info, cell.date. These are IBOutlets I have set up in my CustomTableViewCell file.
class CustomTableViewCell: PFTableViewCell {
#IBOutlet weak var info: UILabel!
#IBOutlet weak var date: UILabel!
#IBOutlet weak var mixCoverPhotoImageView: PFImageView!
}

i have handle the image with the Alamofireimage-framework. The function is really simple.
Alamofire.request(myURL).responseImage(completionHandler: { (response) in
if let ThumbImage = response.result.value {
DispatchQueue.main.async{
cell?. mixCoverPhotoImageView?.image = ThumbImage
}

Related

Swift unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

I'm trying to filter the rows, when I click on some letter it's returning this
unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard)
Here is my List Data Class:
//
// HomeTableViewController.swift
//
//
// Created by Wesley Mota on 06/06/16.
//
//
import UIKit
import Firebase
class HomeTableViewController: UITableViewController, UISearchBarDelegate, UISearchDisplayDelegate {
var ref = FIRDatabase.database().reference()
var nome: String!
var items = [GroceryItem]()
var sobrenome: String!
var filteredItems = [GroceryItem]()
var detailViewController: DetailViewController? = nil
#IBOutlet weak var questionTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
ref.child("Cadastro").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
var newItems = [GroceryItem]()
for item in snapshot.children {
let groceryItem = GroceryItem(snapshot: item as! FIRDataSnapshot)
newItems.append(groceryItem)
}
self.items = newItems
self.tableView.reloadData()
})
// 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 viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
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
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
//return items.count
if (tableView == self.searchDisplayController?.searchResultsTableView){
return self.filteredItems.count
} else{
return items.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomTableViewCell
let groceryItem = items[indexPath.row]
var items1: GroceryItem
if (tableView == self.searchDisplayController?.searchResultsTableView) {
items1 = self.filteredItems[indexPath.row]
} else {
items1 = self.items[indexPath.row]
}
cell.nameLbl.text = groceryItem.nome
cell.lastNameLbl.text = groceryItem.sobrenome
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var items1: GroceryItem
if (tableView == self.searchDisplayController?.searchResultsTableView) {
items1 = self.filteredItems[indexPath.row]
} else {
items1 = self.items[indexPath.row]
}
print(items1.nome)
}
func filterContetnForSearchText(searchText: String, scope: String = "All") {
self.filteredItems = self.items.filter({ (friend: GroceryItem) -> Bool in
var categoryMatch = (scope == "All")
var stringMatch = friend.nome.rangeOfString(searchText)
return categoryMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String?) -> Bool
{
self.filterContetnForSearchText(searchString!, scope: "All")
return true
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool
{
self.filterContetnForSearchText(self.searchDisplayController!.searchBar.text!, scope: "All")
return true
}
}
Here is my CustomTableViewCell
//
// Labels.swift
// enquetepr
//
// Created by Wesley Mota on 06/06/16.
// Copyright © 2016 WesleyMota. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
#IBOutlet weak var nameLbl: UILabel!
#IBOutlet weak var lastNameLbl: UILabel!
}
Class connection with firebase database:
//
// SubmitConnection.swift
// enquetepr
//
// Created by Wesley Mota on 06/05/16.
// Copyright © 2016 WesleyMota. All rights reserved.
//
import Foundation
import Firebase
struct GroceryItem {
var data: NSData = NSData()
let key: String!
let nome: String!
let sobrenome: String!
let ref: FIRDatabaseReference?
// Initialize from arbitrary data
init(nome: String, key: String = "", sobrenome: String) {
self.key = key
self.nome = nome
self.sobrenome = sobrenome
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
key = snapshot.key
nome = snapshot.value!["nome"] as! String!
sobrenome = snapshot.value!["sobrenome"] as! String!
ref = snapshot.ref
}
func toAnyObject() -> AnyObject {
return [
"nome": nome,
"sobrenome": sobrenome,
]
}
}
When I click on some letter >> Image
Here is the Story Board cell id >> Image
I'm using firebase, to store data. It's working (loading) fine, but when I try to filter is happening this error.
There's a few things that could have happened, but first go to your storyboard and click on the cell that defines your 'CustomTableViewCell'.
Ensure the class of the cell is set to 'CustomTableViewCell'.
Set the class of a custom UITableViewCell
Then ensure your you cell identifier is set here:
Set a cell identifyer in storyboard
Now we need to register the cell. This is specifically what the debugger is complaining about.
In your viewDidLoad method of HomeTableViewController add the following code to register the class with the identifier.
tableView.registerClass(CustomTableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")
Try this , It's working for me ,
Check below scenarios for this error ,
-Could you set the Table Cell identifier to "Cell" in your storyboard?, If yes then just add one line of code in viewDidLoad()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
OR
self.tableView.register(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "Cell")
Make sure same identifier "Cell" is also copied at your storyboard's UITableViewCell.
Hope So it's will work for some .
Well, i'm not sure how you configured your search controller but if you have initialized the controller with another controller, you must register programmatically your cell every time the results VC appears on the screen.
init(searchResultsController searchResultsController: UIViewController?)
That is true if searchResultsController != nil
You can register the cell in the following method:
func willPresentSearchController(_ searchController: UISearchController)
As #Damien Bell said, another thing can make this happened is you are make more than one outlet or action with single UIComponent, find and delete it if needed.

UIImageVIew keep coming forward in TableViewCell (using swift, Xcode)

I'm trying to build an app using UITableViewController. I set a UIImageView inside the UITableViewCell.
I've managed to show the image. But, I still can't manage the image to stay at back.
I already use command Editor >> Arrange >> Send to Back, in storyboard, but it's not working.
I also tried this code : cell.sendSubviewToBack(cell.photo)
, but still got the same problem.
can someone help me with this?
FYI, I used ParseUI SDK from parse.com
here is my whole code :
import UIKit
class TableViewController: PFQueryTableViewController, UISearchBarDelegate {
#IBOutlet var searchBar: UISearchBar!
// 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.pullToRefreshEnabled = true
self.paginationEnabled = true
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
// Start the query object
var query = PFQuery(className: "Places")
// query with pointer
query.includeKey("mainPhoto")
// Add a where clause if there is a search criteria
if searchBar.text != "" {
query.whereKey("name", containsString: searchBar.text)
}
// Order the results
query.orderByAscending("name")
// Return the qwuery object
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("tableCell") as! CustomTableViewCell!
if cell == nil {
cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "tableCell")
}
// Extract values from the PFObject to display in the table cell
if let name = object["name"] as? String{
cell.name.text = name
}
if let detail = object["address"] as? String{
cell.detail.text = detail
}
// display initial image
var initialThumbnail = UIImage(named: "question")
cell.photo.image = initialThumbnail
cell.photo.contentMode = UIViewContentMode.Center
// extract image from pointer
if let pointer = object["mainPhoto"] as? PFObject {
if let thumbnail = pointer["photo"] as? PFFile {
cell.photo.file = thumbnail
cell.photo.loadInBackground()
cell.photo.contentMode = UIViewContentMode.ScaleAspectFill
cell.sendSubviewToBack(cell.photo)
}
}
// return the cell
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! DetailViewController
// 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
}
}
override func viewDidLoad(){
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target:self, action:Selector("hideKeyboard"))
tapGesture.cancelsTouchesInView = true
// tableView.addGestureRecognizer(tapGesture)
}
func hideKeyboard(){
tableView.endEditing(true)
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
tableView.reloadData()
// Delegate the search bar to this table view class
searchBar.delegate = self
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// Clear any search criteria
searchBar.text = ""
// Dismiss the keyboard
searchBar.resignFirstResponder()
// Force reload of table data
self.loadObjects()
}
}

Querying an array to populate a table view in Swift using Parse

I'm querying a Parse class for the current user's username. The class column is named Attendants and the array definitely contains the username. When the code is ran, the table isn't populated and no errors are thrown.
Would anybody be able to point out what I'm doing wrong?
Necessary code is shown below:
class EventsViewController: PFQueryTableViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 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 = "Event"
self.textKey = "username"
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: "Event")
var tempname = PFUser.currentUser().username
NSLog(tempname)
query.whereKey("Attendants", equalTo: tempname)
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! PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
cell.selectionStyle = UITableViewCellSelectionStyle.None
}
// Extract values from the PFObject to display in the table cell
cell?.textLabel?.text = object["EventName"] as! String!
cell?.detailTextLabel?.text = object["EventName"] as! String!
cell.selectionStyle = UITableViewCellSelectionStyle.None
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! EventDetailViewController
// 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
}
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
tableView.reloadData()
}
}
All you need to do is write the queryForTable() function.
All your tableView functions are never called.
So something about this would be solution:
class EventsViewController: PFQueryTableViewController {
override init(style: UITableViewStyle, className: String?) {
super.init(style: style, className: className)
self.textKey = "YOUR_PARSE_COLOMN_YOU_WANT_TO_SHOW"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
}
required init!(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "Event")
var tempname = PFUser.currentUser()!.username
NSLog(tempname!)
// This is really ugly.. Please do this via Pointer and not via String.
query.whereKey("Attendants", equalTo: tempname!)
return query
}
}
If you want to use custom cells, you need to create your own TableViewController and implement the logic on the TableViewController itself.
This code is tested in Xcode 6.3 (swift 1.2)
Please keep in mind that you need to init the tableViewController out of the code, like:
var eventsvc = EventsViewController(style: .Plain, className: "Event")
to present it out of a viewcontroller:
self.presentViewController(eventsvc, animated: true, completion: nil)
If you want to use is it in a storyboard see this

Pulling date into subtitle for tableview controller PFTableView

The following is successful at pulling the "category" into the main Title until I start trying get createdAt into the subtitle.
When I start to override func tableView to import the createdAt into the subtitle, the app crashes.
Any thoughts?
import UIKit; import Parse
class UserRecordsTableViewController: 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 = "Event"
self.textKey = "category"
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: "event")
query.orderByAscending("createdAt")
query.whereKey("user", equalTo: PFUser.currentUser())
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as PFTableViewCell!
if cell == nil {
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
//Date for cell subtitle
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateForText = object["createdAt"] as? NSDate
cell.detailTextLabel?.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].
}
}
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
detailTextLabel will be nil in a cell of the default type. If you made the cell in the storyboard, set its type to "Subtitle". If you didn't make it in the storyboard, then change the line where you create the cell to,
cell = PFTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
Heres what I ended up going with and this works so far. The problem was that PFTableViewCell is only intended to work with default not subtitle. So I had to create a custom cell. Next finally found the solution to the date fix on another post.
import UIKit; import Parse
class UserRecordsTableViewController: 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 = "Event"
self.textKey = "category"
self.title = "createdAt"
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: "event")
query.orderByAscending("createdAt")
query.whereKey("user", equalTo: PFUser.currentUser())
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UserRecordsTableViewCell!
if cell == nil {
cell = UserRecordsTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
}
var dateUpdated = object.createdAt as NSDate
var dateFormat = NSDateFormatter()
dateFormat.dateFormat = "EEE, MMM d, h:mm a"
cell.catDate.text = NSString(format: "%#", dateFormat.stringFromDate(dateUpdated))
cell.catTitle.text = object["category"] as String!
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
}*/
}
}

Display data from class subcategory in tableview Parse

I have two classes in the Parse backend.
Classes:
- Category->Kategorien (image, name)
- Subcategory->Unterkategorien (image, name, category(pointer))
I want a TableView for each class. It should be like, I choose a Category in the first TableView and come to the next TableView with all Subcategories of the chosen Category.
With the following code I show the data from the Category class:
import UIKit
class KategorienTableViewController: 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 = "Kategorien"
self.textKey = "name"
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: "Kategorien")
query.orderByAscending("name")
return query
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("KategorienTableCell") as KategorienTableCell!
if cell == nil {
cell = KategorienTableCell(style: UITableViewCellStyle.Default, reuseIdentifier: "KategorienTableCell")
}
// Extract values from the PFObject to display in the table cell
cell.name.text = object["name"] as String!
var thumbnail = object["bild"] as PFFile
var initialThumbnail = UIImage(named: "Kategorien")
cell.bild.image = initialThumbnail
cell.bild.file = thumbnail
cell.bild.loadInBackground()
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 unterkategorienScene = segue.destinationViewController as UnterkategorienTableViewController
// Pass the selected object to the unterkategorien view controller.
if let indexPath = self.tableView.indexPathForSelectedRow() {
let row = Int(indexPath.row)
unterkategorienScene.aktuellesObject = objects[row] as? PFObject
//println(unterkategorienScene.aktuellesObject)
}
}
}
Now I have the problem that I don't know how to display all subcategories (unterkategorien) of the chosen Category in the second TableViewController. The Subcategories have a Parse pointer to the Categories but how should I use that in this case?
At the moment it displays all Subcategories in the second Tableview when I first choose a Category in the first TableView.
My code of the second TableViewController actually looks like this:
import UIKit
class UnterkategorienTableViewController: PFQueryTableViewController {
var aktuellesObject : PFObject?
// 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 = "Unterkategorien"
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("UnterkategorienTableCell") as UnterkategorienTableCell!
if cell == nil {
cell = UnterkategorienTableCell(style: UITableViewCellStyle.Default, reuseIdentifier: "UnterkategorienTableCell")
}
if let objecti = aktuellesObject?{
// Extract values from the PFObject to display in the table cell
cell.unterkategorienName.text = object["name"] as String!
//println(object["name"].objectId)
var thumbnail = object["bild"] as PFFile
var initialThumbnail = UIImage(named: "Kategorien")
cell.unterkategorienBild.image = initialThumbnail
cell.unterkategorienBild.file = thumbnail
cell.unterkategorienBild.loadInBackground()
}
return cell
}
}
Why don't you create the void which you created in the main (KategorienTableViewController) called queryForTable()?
But then you need the current category which you have to pass via the prepareForSegue (what you already did) but you need to pass the Category and not the subcategory.
It would look something like this:
KategorienTableViewController:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var unterkategorienScene = segue.destinationViewController as UnterkategorienTableViewController
// Pass the selected object to the unterkategorien view controller.
if let indexPath = self.tableView.indexPathForSelectedRow() {
let row = Int(indexPath.row)
unterkategorienScene.aktuellesObject = objects[row] as? PFObject
//println(unterkategorienScene.aktuellesObject)
}
}
UnterkategorienTableViewController:
override func queryForTable() -> PFQuery! {
var query = PFQuery(className: self.parseClassName)
query.whereKey("category", equalTo: aktuellesObject)
return query
}
ps. Wie ich sehe sprichst du Deutsch, probier nicht Deutsch und Englisch während dem Programmieren zu vermischen das sorgt für Chaos.

Resources