I'm new to swift programming.
I wrote a code which gets xml
output from rss
feed and parse it into NSDATA
type,
then I want to get title
and image
src
values from it in a loop and send them to a table view to create a list.
when I get those values manually I mean like :
let appName = xml["rss"]["channel"]["item"][0]["title"].element!.text!
let appUrl = xml["rss"]["channel"]["item"][0]["description"]["img"].element!.attributes["src"]
my code works ok and one item creates in table view correctly. but the problem is when I want to get all values from xml file.
I couldn't create and array of the xml which is NSDATA type, not a string to be able to loop through it.
all I could manage to work is the below code which returns all xml tags value which I don't want that :
func enumerate(indexer: XMLIndexer, level: Int) {
for child in indexer.children {
let appName = child.element!.text
let appUrl = child.element!.attributes["src"]
let ap = Apps(name: appName , img : appUrl)
self.tableData.append(ap)
self.tableView.reloadData()
enumerate(child, level: level + 1)
}
}
enumerate(xml, level: 0)
Any Idea how to get those values in a loop without mistaking or getting other values?
here is my code :
let url = NSURL(string: "http://razavitv.aqr.ir/index/rss/2")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
let processedString = (dataString as NSString).stringByReplacingOccurrencesOfString("<![CDATA[", withString: "").stringByReplacingOccurrencesOfString("]]", withString: "") as String
let data: NSData = processedString.dataUsingEncoding(NSUTF8StringEncoding)!
let xml = SWXMLHash.parse(data)
// let appName = xml["rss"]["channel"]["item"][0]["title"].element!.text!
// let appUrl = xml["rss"]["channel"]["item"][0]["description"]["img"].element!.attributes["src"]
//
// let ap = Apps(name: appName , img : appUrl)
// self.tableData.append(ap)
//
// self.tableView.reloadData()
func enumerate(indexer: XMLIndexer, level: Int) {
for child in indexer.children {
let appName = child.element!.text
let appUrl = child.element!.attributes["src"]
let ap = Apps(name: appName , img : appUrl)
self.tableData.append(ap)
self.tableView.reloadData()
enumerate(child, level: level + 1)
}
}
enumerate(xml, level: 0)
}
task.resume()
very simple solution : just need to create a for loop with indexer inside.
here is the code :
//one root element
let count = xml["rss"]["channel"]["item"].all.count
for var i = 0; i < count; i++ {
let appName = xml["rss"]["channel"]["item"][i]["title"].element!.text!
let appUrl = xml["rss"]["channel"]["item"][i]["description"]["img"].element!.attributes["src"]
let ap = Apps(name: appName , img : appUrl)
self.tableData.append(ap)
self.tableView.reloadData()
}