草庐IT

ios - Xml 解析器委托(delegate)不在 Swift 中调用

coder 2023-09-17 原文

我有一个提供 xml 响应的网络服务。我想解析并显示在表格中。但是我的 XMLParser 委托(delegate)没有被调用。我是 swift 的新手。请帮助任何帮助将不胜感激,

class ViewController: UIViewController,NSXMLParserDelegate,UITableViewDelegate {
        var element:String?
        var titles:NSMutableString?
        var link:NSMutableString?
        var tableData:NSMutableArray?
        var dict:NSMutableDictionary?
     @IBOutlet weak var table: UITableView?
        override func viewDidLoad() {
            super.viewDidLoad()
            dict = NSMutableDictionary()
            tableData = NSMutableArray()
            let url = NSURL(string: "hp?keytext=s")
            let theRequest = NSURLRequest(URL: url)

            NSURLConnection.sendAsynchronousRequest(theRequest, queue: nil, completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
                if data.length > 0 && error == nil {

                 //var   parser=NSXMLParser(data: data)
               var parser = NSXMLParser(contentsOfURL: url)
                    parser.delegate=self
                    parser.shouldResolveExternalEntities=false
                 parser.parse()
                }
            })
            // Do any additional setup after loading the view.




        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

        func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {

            // Return the number of rows in the section.
            return tableData!.count
        }

        func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

                  var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell


            if !(cell != nil) {
                       cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")}



            var a:NSString
            var b:String

            a = tableData?.objectAtIndex(indexPath.row).objectForKey("title") as NSString
            b = tableData?.objectAtIndex(indexPath.row).objectForKey("city") as NSString

            cell?.textLabel?.text=a;
             cell?.detailTextLabel?.text=b




            return cell




        }

        func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat

        {

            return 78;

        }


        func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String, qualifiedName qName: String, attributes attributeDict: [NSObject : AnyObject]) {
            element=elementName
            if element=="restaurant"
            {
                titles=NSMutableString()
                link=NSMutableString()
            }

        }

        func parser(parser: NSXMLParser, foundCharacters string: String) {
            if element=="title"
            {
                titles?.appendString(string)
            }
            else if element=="city"
            {
                link!.appendString(string)
            }
        }


        func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String, qualifiedName qName: String) {
            if elementName == "restaurant"
            {
                dict?.setValue(titles, forKeyPath: "title")
                dict?.setValue(link, forKeyPath: "city")
                tableData?.addObject(dict!)

            }
        }

        func parserDidEndDocument(parser: NSXMLParser!){

            table?.reloadData()

        }

    }

最佳答案

您不需要在 viewDidLoad 方法中使用 sendAsynchronousRequest 而不是使用此代码:

在所有函数之外声明parser 变量。

然后在您的 viewDidLoad 方法中将您的代码替换为以下代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://images.apple.com/main/rss/hotnews/hotnews.rss")  //this is example URL

    parser = NSXMLParser(contentsOfURL: url)!
    parser.delegate = self
    parser.parse()

}

你的完整代码将是:

import UIKit

class ViewController: UIViewController,NSXMLParserDelegate,UITableViewDelegate, UITableViewDataSource {    //You will need UITableViewDataSource here.

    var parser : NSXMLParser = NSXMLParser()
    var element:String?
    var titles:NSMutableString?
    var link:NSMutableString?
    var tableData:NSMutableArray?
    var dict:NSMutableDictionary?

    @IBOutlet weak var table: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string: "http://images.apple.com/main/rss/hotnews/hotnews.rss")

        parser = NSXMLParser(contentsOfURL: url)!
        parser.delegate = self
        parser.parse()

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        // Return the number of rows in the section.
        return tableData!.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell


        if !(cell != nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")}
        var a:NSString
        var b:String

        a = tableData?.objectAtIndex(indexPath.row).objectForKey("title") as! NSString
        b = tableData?.objectAtIndex(indexPath.row).objectForKey("city") as! NSString as String

        cell?.textLabel?.text = a as String;
        cell?.detailTextLabel?.text = b

        return cell!

    }

    func tableView(tableView:UITableView, heightForRowAtIndexPath indexPath:NSIndexPath)->CGFloat

    {

        return 78;

    }

    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
        element=elementName
        if element=="restaurant"
        {
            titles=NSMutableString()
            link=NSMutableString()
        }

    }

    func parser(parser: NSXMLParser, foundCharacters string: String?) {
        if element=="title"
        {
            titles?.appendString(string!)
        }
        else if element=="city"
        {
            link!.appendString(string!)
        }
    }


    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "restaurant"
        {
            dict?.setValue(titles, forKeyPath: "title")
            dict?.setValue(link, forKeyPath: "city")
            tableData?.addObject(dict!)

        }
    }

    func parserDidEndDocument(parser: NSXMLParser){

        table?.reloadData()

    }

}

我也更新了你的委托(delegate)函数。

并检查您是否从您的 URL 获取数据。

我建议你关注THIS首先教程,这将帮助您理解所有内容。

关于ios - Xml 解析器委托(delegate)不在 Swift 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32087989/

有关ios - Xml 解析器委托(delegate)不在 Swift 中调用的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  5. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  6. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  7. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  8. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

随机推荐