XML Parser没有将数据组织到表

时间:2016-06-03 01:42:10

标签: swift xml-parsing

我正在创建一个应用程序,它涉及解析网站的XML文件并将信息放入表格视图中。目前,故事板作为标签视图应用程序,其中有4个表视图控制器连接到它。我已经开发了附带的类文件并设置其中一个控制器来运行它。但是,该类虽然没有错误,但不会返回并创建任何表。屏幕是空白的,就像之前有任何swift文件一样。该文件如下所示

import UIKit

class Newspage: UITableViewController, NSXMLParserDelegate
{
    var parser: NSXMLParser = NSXMLParser()
    var info: [newsarticle] = []
    var postTitle: String = String()
    var postDesc: String = String()
    var eName: String = String()
    override func viewDidLoad() {
        super.viewDidLoad()
        super.viewDidLoad()
        let url:NSURL = NSURL(string: "http://brrsd.k12.nj.us/rss/News.xml")!
        parser = NSXMLParser(contentsOfURL: url)!
        parser.delegate = self
        parser.parse()

        // 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.
    }
    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI namespaceURI: String?, qualifiedName qualifiedName: String?, attributes attributeDict: [String : String])
    {
        eName = elementName
        if elementName == "item" {
            postTitle = String()
            postDesc = String()
        }
    }

    func parser(parser: NSXMLParser!, foundCharacters string: String!) {
        let data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        if (!data.isEmpty) {
            if eName == "title" {
                postTitle += data
            } else if eName == "description" {
                postDesc += data
            }
        }
    }

    func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
        if elementName == "item" {
            let newsart: newsarticle = newsarticle()
            newsart.title = postTitle
            newsart.description = postDesc
            info.append(newsart)
        }
    }

    // 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 info.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        let news: newsarticle = info[indexPath.row]
        cell.textLabel!.text = news.title
        return cell
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false 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
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } 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
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // 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.
        // Pass the selected object to the new view controller.
    }
    */

}

错误在哪里? 注意:newsarticle类只包含2个变量,标题和描述。

1 个答案:

答案 0 :(得分:0)

我认为您的问题是,当您解析XML时,不要让您的表自行刷新。

您需要通过使用tableView.reloadData()告诉表在需要时刷新自己。

您可以在每个元素的末尾或通过在委托函数parserDidEndDocument(_ parser:NSXMLParser)中调用reloaData来结束解析时执行此操作。

此外,您不需要在viewDidLoad中调用两次super.viewDidLoad()。

我是你我也会将viewController类和解析器委托分成两个独立的类。

你的cellForRowAtIndexPath也困扰着我: 我不认为您需要第二个参数(indexPath)来获取单元格。您不希望单元格成为IndexPath,而是返回要放入IndexPath的单元格。 tableView.dequeueReusableCellWithIdentifier("Cell")应该为您提供一个包含' Cell'可重用的标识符。例如,当您向下滚动顶部不再显示的单元格时,可以重复使用以显示在底部。

这是我如何实现这个功能

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: UITableViewCell
    if let reusedCell = tableView.dequeueReusableCellWithIdentifier("Cell") {
        cell = reusedCell 
    } else {
        cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell") 
    }

    if let label = cell.textLabel {
        let news = info[indexPath.row]
        label.text = news.title
    }
    return cell
}