【发布时间】:2018-10-21 05:54:42
【问题描述】:
我想从 XML URL 中获取值,但没有任何错误。我试图理解我的错误。这是我的代码:
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,XMLParserDelegate {
@IBOutlet weak var tblView: UITableView!
var parser = XMLParser()
var haberler = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var link = NSMutableString()
override func viewDidLoad() {
super.viewDidLoad()
parsinDataFromURL()
}
我的 xml 解析函数
func parsinDataFromURL() {
haberler = []
parser = XMLParser(contentsOf: NSURL(string: "http://www.haberturk.com/rss/kategori/gundem.xml")! as URL)!
parser.delegate = self
parser.parse()
tblView.reloadData()
}
didStartElement、FoundCharacters 和 didEndElement 函数
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if (elementName as NSString) .isEqual(to: "item") {
elements = NSMutableDictionary()
elements = [:]
title1 = NSMutableString()
title1 = " "
link = " "
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if element .isEqual(to: "title") {
title1.append(string)
}
else if element.isEqual(to: "link") {
link.append(string)
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if (elementName as NSString) . isEqual(to: "item") {
if !title1.isEqual(nil) {
elements.setObject(title1, forKey: "title" as NSCopying)
}
if !link .isEqual(nil) {
elements.setObject(link, forKey: "link" as NSCopying)
}
haberler.addObjects(from: [elements])
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return haberler.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: ("myCell"))! as UITableViewCell
if (cell.isEqual(NSNull.self)) {
cell = Bundle.main.loadNibNamed("myCell", owner: self, options: nil)![0] as! UITableViewCell
}
cell.textLabel?.text = (haberler.object(at: indexPath.row) as AnyObject).value(forKey: "title") as? String
cell.detailTextLabel?.text = (haberler.object(at: indexPath.row) as AnyObject).value(forKey: "title") as? String
return cell
}
}
当我在模拟器中运行时,UITableView 是空的(empty UITableViewscreen:https://imgur.com/a/KglwSvS)
【问题讨论】:
-
这是斯威夫特。你应该使用 Swift 类。使用 Swift 字典,而不是
NSMutableDictionary。使用 Swift 数组,而不是NSMutableArray。使用String,而不是NSMutableString。使用URL,而不是NSURL。 -
你做了什么调试?是否调用了任何 XMLParse 委托方法?您的
haberler数组是否被填充? -
我刚刚打印了'haberler',它总是显示:{ link = " ";标题=“”; },
标签: ios swift xml-parsing