TableView Parse Swift 数据未显示在应用程序中

Posted

技术标签:

【中文标题】TableView Parse Swift 数据未显示在应用程序中【英文标题】:TableView Parse Swift data not showing within the app 【发布时间】:2015-05-20 14:21:19 【问题描述】:

我刚开始编码,我搜索了几篇帖子,但我找不到为什么我的应用程序中的数据没有显示。

它正在获取我的数据,但我不明白如何将其添加到 tableView 我的第一个代码“覆盖 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell”仍然存在,并且请解释为什么它不起作用。想了解它为什么不起作用。

class MasterTableViewController: PFQueryTableViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate 

var noteObjects: NSMutableArray! = NSMutableArray()

@IBAction func logoutAction(sender: UIBarButtonItem) 
    PFUser.logOut()
    viewDidAppear(true)


// 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 = "Note"
    self.textKey = "title"
    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: "Note")
    query.orderByAscending("updatedAt")
    return query


override func viewDidAppear(animated: Bool) 
    super.viewDidAppear(animated)
    
    if (PFUser.currentUser() == nil) 
        var logInViewController = PFLogInViewController()
        
        logInViewController.delegate = self
        
        var signUpViewController = PFSignUpViewController()
        
        signUpViewController.delegate = self
        
        logInViewController.signUpController = signUpViewController
        
        self.presentViewController(logInViewController, animated: true, completion: nil)
        
    else 
        
        //self.fetchAllObjectsFromLocalDatastore()
        
        //self.fetchAllObjects()
    


func fetchAllObjectsFromLocalDatastore() 
    
    var query: PFQuery = PFQuery(className: "Note")
    
    //query.cachePolicy = .CacheElseNetwork
    
    query.fromLocalDatastore()
    
    query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
    
    query.findObjectsInBackgroundWithBlock 
        (objects: [AnyObject]?, error: NSError?) -> Void in
        
        if (error == nil) 
            
            if let objects = objects as? [PFObject] 
                for object in objects 
                    println(object.objectId)
                
            
            
            var temp: PFObject = PFObject()
            
            self.noteObjects = temp.mutableCopy() as! NSMutableArray
            
            self.tableView.reloadData()
            
        else 
            
            println(error!.userInfo)
        
    


func fetchAllObjects() 
    
    PFObject.unpinAllObjectsInBackgroundWithBlock(nil)
    
    var query: PFQuery = PFQuery(className: "Note")
    
    //query.cachePolicy = .CacheElseNetwork
    
    query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
    
    query.findObjectsInBackgroundWithBlock 
        (objects: [AnyObject]?, error: NSError?) -> Void in
        
        if (error == nil) 
            
            PFObject.pinAllInBackground(objects, block: nil)
            
            self.fetchAllObjectsFromLocalDatastore()
            
        else 
            
            println(error!.userInfo)
        
    



// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 0


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.noteObjects.count


//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! MasterTableViewCell!
    if cell == nil 
        cell = MasterTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    
    
    // Extract values from the PFObject to display in the table cell
    if let titleLabel = object?["title"] as? String 
        cell?.masterTitleLabel?.text = titleLabel
    
    if let textView = object?["text"] as? String 
        cell?.masterTextLabel?.text = textView
    
    
    return cell


//First try did find the code above afterwards
/*override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MasterTableViewCell

    // Configure the cell...
    
    var object: PFObject = self.noteObjects.objectAtIndex(indexPath.row) as! PFObject
    
    cell.masterTitleLabel?.text = object["title"] as? String
    cell.masterTextLabel?.text = object["text"] as? String
    
    return cell
*/

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    
    self.performSegueWithIdentifier("editNote", sender: self)


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
    
    var upcoming: AddNoteTableViewController = segue.destinationViewController as! AddNoteTableViewController
    
    if (segue.identifier == "editNote") 
        
        let indexPath = self.tableView.indexPathForSelectedRow()!
        
        var object: PFObject = self.noteObjects.objectAtIndex(indexPath.row)as! PFObject
        
        upcoming.object = object;
        
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    



// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 
    // Return NO if you do not want the specified item to be editable.
    return true



// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
    if editingStyle == .Delete 
        // Delete the row from the data source
        let objectToDelete = noteObjects?[indexPath.row] as! PFObject
        objectToDelete.deleteInBackgroundWithBlock 
            (success: Bool, error: NSError?) -> Void in
            if (success) 
                // Force a reload of the table - fetching fresh data from Parse platform
                self.fetchAllObjects()
             else 
                // There was a problem, check error.description
            
        
     else if editingStyle == .Insert 
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    



//Signup and Login ViewController created by Parse
func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool 
    
    logInController.fields = (PFLogInFields.UsernameAndPassword
        | PFLogInFields.LogInButton
        | PFLogInFields.SignUpButton
        | PFLogInFields.PasswordForgotten)
    
    if (!username.isEmpty || !password.isEmpty) 
        return true
    else  
        return false
    


func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) 
    self.dismissViewControllerAnimated(true, completion: nil)
    


func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) 
    println("Failed to log in...")


func signUpViewController(signUpController: PFSignUpViewController, shouldBeginSignUp info: [NSObject : AnyObject]) -> Bool 
    
    if let password = info["password"] as? String 
        
        return count(password.utf16) >= 8
        
     else 
        return false
    


func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) 
    self.dismissViewControllerAnimated(true, completion: nil)


func signUpViewController(signUpController: PFSignUpViewController, didFailToSignUpWithError error: NSError?) 
    println("Failed to sign up...")


func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController) 
    println("User dissmissed sign up.")


更新:更改 numberOfSections 没有帮助

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
return 1


已解决

现在可以了,修改了这部分代码

func fetchAllObjectsFromLocalDatastore() 
    
    var query: PFQuery = PFQuery(className: "Note")
    
    //query.cachePolicy = .CacheElseNetwork
    
    query.fromLocalDatastore()
    
    query.whereKey("username", equalTo: PFUser.currentUser()!.username!)
    
    query.findObjectsInBackgroundWithBlock 
        (objects: [AnyObject]?, error: NSError?) -> Void in
        
        if (error == nil) 
            
            if let objects = objects as? [PFObject] 
                for object in objects 
                    println(object.objectId)
                
            
            
            //var temp: PFObject = PFObject()
            
            //self.noteObjects = temp.mutableCopy() as! NSMutableArray
            
            //println(self.noteObjects)
            
            self.tableView.reloadData()
            
        else 
            
            println(error!.userInfo)
        
    

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return objects!.count

【问题讨论】:

你有什么物品吗? IE。是 self.noteObjects.count > 0? 我将 self.noteObjects.count 更改为 objects!.count,现在可以使用了,非常感谢。 请问您为什么不使用 Parse PFQueryTableViewController?代码非常干净。看看这里。 blog.bizzi-body.com/2015/02/05/… 【参考方案1】:

@DenisE 我遇到了同样的麻烦,您添加 self.tableView.reloadData() 的解决方案修复了它。我们必须这样做的原因是我相信因为视图已经出现并且之后查询了数据,所以除非我们在视图中重新加载查询的数据,否则它不会反映在 UI 中。

【讨论】:

【参考方案2】:

您需要将您的部分数设置为 1,否则没有要显示的部分,因此也没有内容。

override func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    return 1

【讨论】:

谢谢,但我仍然看不到我的任何内容,尝试早点更改此号码。这就是为什么我不明白为什么它不起作用。 Pascal_AC 返回常量 1 无济于事,它应该等于数据计数,因此 objects!.count @anji20 所以你想为每个对象创建一个部分吗?我认为 objects!.count 属于 numbersOfRowsInSection 函数,但不属于 numberOfSection^^

以上是关于TableView Parse Swift 数据未显示在应用程序中的主要内容,如果未能解决你的问题,请参考以下文章

parse.com swift - 在 tableView 单元格中取消固定和删除对象

如何在 Swift Xcode 6.4 的 TableView 中显示 Parse 数组

iOS如何在少数Data表中搜索数据Parse swift 4

Json数据未显示在tableView swift 5上

从 Parse.com (Swift) 检索数据

Swift:表格单元格未正确设置按钮