So I've just updated my swift to 2.0 and obviously a couple of errors appeared in my code.
Thats what I have right now.
unc loadRssFeed(data: NSURL) {
var myRssParser : ParserManager = ParserManager.alloc().initWithURL(data) as! ParserManager
myRssFeed = myRssParser.feeds
tableView.reloadData()
}
Fixit suggests to change 'var' to 'let' and use object initializer instead of alloc(). But the problem is I've never used it before (granted my Swift experience is like four weeks).
Should I follow fixit instruction?
And how do I fix the alloc() problem.
Thanks!
Updated wit parser code:
class ParserManager: NSObject, NSXMLParserDelegate {
var parser = NSXMLParser()
var feeds = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var ftitle = NSMutableString()
var link = NSMutableString()
var fdescription = NSMutableString()
var fdate = NSMutableString()
func initWithURL(url :NSURL) -> AnyObject {
startParse(url)
return self
}
func startParse(url :NSURL) {
feeds = []
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
}
func allFeeds() -> NSMutableArray {
return feeds
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.element = elementName
if self.element == "item" {
self.ftitle = ""
self.fdescription = ""
self.fdate = ""
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if (elementName as NSString).isEqualToString("item") {
if ftitle != "" {
elements.setObject(ftitle, forKey: "title")
}
if fdescription != "" {
elements.setObject(fdescription, forKey: "description")
}
if fdate != "" {
elements.setObject(fdate, forKey: "pubDate")
}
feeds.addObject(elements)
}
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
if element.isEqualToString("title") {
ftitle.appendString(string!)
}else if element.isEqualToString("description") {
fdescription.appendString(string!)
}else if element.isEqualToString("pubDate") {
fdate.appendString(string!)
}
}
}
The fix should look like this:
let myRssParser = ParserManager(URL: data) as! ParserManager
Or maybe like this, depends upon how ParserManager has been written:
let myRssParser = ParserManager(url: data) as! ParserManager
There's even a possibility that you don't have to use the argument name:
let myRssParser = ParserManager(data) as! ParserManager
As discussed above, you should not call alloc and init... methods directly. Furthermore, the ParserManager class should not have a initWithURL method, but rather an init method with a URL parameter. The existing code is appearing to follow Objective-C patterns, but Swift has its own conventions.
But more broadly, I would advise against performing synchronous network requests, and when you're calling NSXMLParser(contentsOfURL:), that's what's happening. It's better to request data asynchronously, and then refactor the code to follow asynchronous patterns (e.g. completionHandler closures). For example:
class ParserManager: NSObject, NSXMLParserDelegate {
/// The NSMutableArray used internally by this class
private var feeds = NSMutableArray()
/// Initiate parsing asynchronously; note, I'm returning the `NSURLSessionTask` in case you want to cancel it at some later point
func parse(URL: NSURL, completionHandler: (NSMutableArray?, NSError?)->()) -> NSURLSessionTask {
let task = NSURLSession.sharedSession().dataTaskWithURL(URL) { data, response, error in
guard data != nil else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, error)
}
return
}
let parser = NSXMLParser(data: data!)
parser.delegate = self
if parser.parse() {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(self.feeds, nil)
}
} else {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, parser.parserError)
}
}
}
task.resume()
return task
}
// NSXMLParserDelegate methods implemented here
}
Then, you can use the completion handler syntax to specify what you want to do when the network request and parsing is done:
let URL = NSURL(string: "...")
let myRssParser = ParserManager()
myRssParser.parse(URL) { feeds, error in
guard feeds != nil else {
print(error)
return
}
// use `feeds` here, e.g.
self.feeds = feeds // update your local property
self.tableView.reloadData() // and reload the table
}
// but don't use `feeds` here, since it won't be done by the time we get here
Related
I am having an issue in which I am parsing a String value from an API and I am trying to assign it to an UILabel. I have tested updating the label in the exact same position as it is now by setting the label (lblNamedata) to a String using the format:
self.lblNameData.text = "hello"
and it has worked fine.
I currently have:
if success {
print("parse success!")
print(strXMLData)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblNameData.text=self.strXMLData
})
} else {
print("parse failure!")
}
and this isn't working.
Below is my complete current code:
import UIKit
class ViewController: UIViewController,NSXMLParserDelegate {
var strXMLData:String = ""
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var parser = NSXMLParser()
#IBOutlet weak var lblNameData: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let url:String="http://www.stands4.com/services/v2/quotes.php?uid=idhere&tokenid=tokenhere&searchtype=xxxx&query=xxxx"
let urlToSend: NSURL = NSURL(string: url)!
// Parse the XML
parser = NSXMLParser(contentsOfURL: urlToSend)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse success!")
print(strXMLData)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.lblNameData.text=self.strXMLData
})
} else {
print("parse failure!")
}
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="quote" || elementName=="author" || elementName=="result")
{
if(elementName=="quote"){
passName=true;
}
passData=true;
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement="";
if(elementName=="quote" || elementName=="author" || elementName=="result")
{
if(elementName=="quote"){
passName=false;
}
passData=false;
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if(passName){
strXMLData=strXMLData+"\n\n"+string
}
if(passData)
{
// print(string)
print("work")
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog("failure error: %#", parseError)
}
}
UPDATE: So I believe I found the error: in my parser function I'm setting strXMLData = strXMLData + "\n\n" + string but after I delete the \n\n I can see that my label updates...why is this?
Alright, so after many instances of trial and error, I think I figured out the answer.
Something was up in my Main.storyboard that didn't like me creating multiple lines in the UILabel, so what I did was click on the label and navigated to the Attributes Inspector. I set the "Lines" parameter to 0 and I was able to see my text!
I am trying to parse a xml file direct from a URL the code has no errors, and the app opens fine but the tableview is empty. here is the link and the code I have used, if I can get some guidance it would be greatly appreciated.
I initially built this through a tutorial (just learning the ropes)
import UIKit
class firecallViewController: UIViewController, NSXMLParserDelegate{
#IBOutlet var tbData: UITableView?
var parser = NSXMLParser()
var posts = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var title1 = NSMutableString()
var date = NSMutableString()
override func viewDidLoad()
{
super.viewDidLoad()
self.beginParsing()
}
func beginParsing()
{
posts = []
parser = NSXMLParser(contentsOfURL:(NSURL(string:"https://example.com/bushfirealert/bushfireAlert.xml"))!)!
parser.delegate = self
parser.parse()
tbData!.reloadData()
}
//XMLParser Methods
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
element = elementName
if (elementName as NSString).isEqualToString("item")
{
elements = NSMutableDictionary()
elements = [:]
title1 = NSMutableString()
title1 = ""
date = NSMutableString()
date = ""
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
if (elementName as NSString).isEqualToString("item") {
if !title1.isEqual(nil) {
elements.setObject(title1, forKey: "title")
}
if !date.isEqual(nil) {
elements.setObject(date, forKey: "date")
}
posts.addObject(elements)
}
}
func parser(parser: NSXMLParser, foundCharacters string: String)
{
if element.isEqualToString("title") {
title1.appendString(string)
} else if element.isEqualToString("pubDate") {
date.appendString(string)
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return posts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell")!
if(cell.isEqual(NSNull)) {
cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil)[0] as! UITableViewCell;
}
cell.textLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("title") as! NSString as String
cell.detailTextLabel?.text = posts.objectAtIndex(indexPath.row).valueForKey("date") as! NSString as String
return cell as UITableViewCell
}
}
Updated answer
You told me in the comments that you don't have to use NSXMLParser.
In this case, I have an easy solution for your parsing: use CheatyXML, a very simple library.
First, follow the easy install intructions.
Then make a parser with your URL:
import CheatyXML
let feedUrl = NSURL(string: "https://example.com/bushfirealert/bushfireAlert.xml")!
let parser = XMLParser(contentsOfURL: feedUrl)
And safely unwrap all values as if you were subscripting dictionaries, and use the .string property to get the string fields contents.
Like this:
if let parser = parser,
channel = parser["channel"],
title = channel["title"].string,
link = channel["link"].string,
description = channel["description"].string,
docs = channel["docs"].string,
generator = channel["generator"].string {
print(title)
print(link)
print(description)
print(docs)
print(generator)
}
Result:
QFES Current Incidents
http://bneags01.desqld.internal/publicfeed/PublicRssFeed.aspx
QFES Current Incidents
http://www.rssboard.org/rss-specification
Argotic Syndication Framework
Now instead of my series of print you call a method of yours to populate your variables and then you reload the table view, and you're set.
Old answer
NSXMLParser works asynchronously, so when you reload your table in beginParsing(), the data is not parsed yet.
You need to reload the table when the parser has finished parsing.
Luckily, there's a callback for that.
Remove tbData!.reloadData() from beginParsing() and add this delegate method to your view controller instead:
func parserDidEndDocument(parser: NSXMLParser) {
tbData!.reloadData()
}
pretty new at swift. Currently, I have a program where on the click of a button I make an NSURL request, take that response, parse the XML, and store the data I need into a array[String]. Pressing this button also serves as a segue into a table view controller which will be dynamically populated with the info from the array.
What I'm seeing is that the segue is occurring and the next VC is being passed an empty array before my request is even complete and response is parsed. (this is all based on the print statements I've inserted in just about every other line to track the execution of my code).
How can I go about this so that the segue does not take me to the next VC until my response has been parsed?
class start: UIViewController, NSURLConnectionDelegate, NSXMLParserDelegate {
var timeArr:[String] = []
var url = "myurl.com"
#IBOutlet weak var get2: UIButton!
#IBAction func getAction(sender: UIButton) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
httpGet (request) {
(data, error) -> Void in
if error != nil {
print(error)
mainInstance.arrivalArr.append("no arrival times")
} else {
self.beginParsing()
print(data)
}
}
}
func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) {
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
callback("", error!.localizedDescription)
} else {
var result = NSString(data: data!, encoding:
NSUTF8StringEncoding)!
self.data2 = data!
callback(result as String, nil)
}
}
task.resume()
}
func beginParsing()
{
posts = []
parser = NSXMLParser(data: data2)
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
element = elementName
if (elementName as NSString).isEqualToString("prd")
{
// more code
}
}
func parser(parser: NSXMLParser, foundCharacters string: String)
{
if element.isEqualToString("prdtm") {
//code
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
if (elementName as NSString).isEqualToString("prd") {
if !title1.isEqual(nil) {
//code
}
//code
finalTimeStr = getTime(finalTimeStr)
timeArr.append(finalTimeStr)
}
}
func getTime (time: String) -> String{
var arrivalTime = time
//code to trim and format time here
var timeA = getTimeDiff(arrivalTime)
timeA = trimToMin(timeA)
return timeA
}
func trimToMin (timeToTrim : String) -> String {
var timeInMin = timeToTrim
//code to trim to minutes
return substring2
}
func getTimeDiff (time: String) -> String{
//code to find time difference
let ret = stringFromTimeInterval(diff)
return ret
}
func stringFromTimeInterval(interval: NSTimeInterval) -> String {
//code to format interval
return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let CDview = segue.destinationViewController as? ListView {
CDview.timeArr = timeArr
//CDview.timeArr = mainInstance.arrivalArr
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
timeArr = testArr
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Not sure where I went wrong. It's particularly confusing because if I use hardcoded strings and jump straight into getTimeDiff then it works perfectly fine and my table view on the next VC also looks great. Would appreciate any help. I've literally moved this code around for the last 12 hours trying to understand why it's not working.
Add a segue from view controller ( and not from UIButton) in storyboard . And name it as you want ( storyboard identifier ) . Perform the segue programmatically with performSegue(...) after you parsed the data .
During my app development I've encountered a specific problem.
I've a database which contains following columns: Dossier_Title, Dossier_Name, Dossier_Category and Dossier_Description. The Description is uniqe for every Dossier.
First of all I'm calling my WebService which selects unique Dossier_Title and forms an xml page. After that app parse this page and forms a number of unique cells in table View. Also it forms an array which consists of Dossier_Title and Dossier_category.
Now I want to form a new tableView which would consist of Dossier_Name and Dossier_Description based on the Dossier_Category I've achieved on previous step. For this I want to call a new WebService and parse it using that Category as condition.
My question is: how can I pass Dossier_category to my second parser so I can use it as condition?
Here is my first parser code I assume the second one would be pretty much the same with addition of some new conditions
class DossierParser: NSObject, NSXMLParserDelegate {
var parser = NSXMLParser()
var feeds = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var ftitle = NSMutableString()
var link = NSMutableString()
var fdescription = NSMutableString()
var fdate = NSMutableString()
var fcategory = NSMutableString()
// initilise parser
/*
func initWithURL(url :NSURL) -> AnyObject {
startParse(url)
return self
}
*/
init(URL: NSURL){
super.init()
startParse(URL)
}
func startParse(url :NSURL) {
feeds = []
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
}
func allFeeds() -> NSMutableArray {
return feeds
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.element = elementName
if self.element == "News" {
elements = NSMutableDictionary()
elements = [:]
ftitle = NSMutableString()
ftitle = ""
fdescription = NSMutableString()
fdescription = ""
fdate = NSMutableString()
fdate = ""
fcategory = NSMutableString()
fcategory = ""
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if (elementName as NSString).isEqualToString("News") {
if ftitle != "" {
elements.setObject(ftitle, forKey: "DosNum")
}
if fcategory != "" {
elements.setObject(fcategory, forKey: "Dossier_number")
}
if fdate != "" {
elements.setObject(fdate, forKey: "Date_Text")
}
feeds.addObject(elements)
}
}
func parser(parser: NSXMLParser, foundCharacters string: String?) {
if element.isEqualToString("DosNum") {
ftitle.appendString(string!)
}else if element.isEqualToString("Date_Text") {
fdate.appendString(string!)
}else if element.isEqualToString("Dossier_number"){
fcategory.appendString(string!)
}
}
And here is my first TableView code.
var myFeed : NSArray = []
var url: NSURL = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
// Cell height.
self.tableView.rowHeight = 70
self.tableView.dataSource = self
self.tableView.delegate = self
//url = NSURL(string: "https://www.kpmg.com/_layouts/feed.aspx?xsl=1&web=/RU/ru/IssuesAndInsights/RSSFeeds&page=207b36b2-20f7-407f-a9ec-a09f191fd84b&wp=9810a349-6086-489d-ad03-40c06f6669f6")!
//url = NSURL(string: "http://www.skysports.com/rss/0,20514,11661,00.xml")!
// url = NSURL(scheme: "https", host: "www.kpmg.com", path: "/_layouts/feed.aspx?xsl=1&web=/RU/ru/IssuesAndInsights/RSSFeeds&page=207b36b2-20f7-407f-a9ec-a09f191fd84b&wp=9810a349-6086-489d-ad03-40c06f6669f6")!
//(scheme: "http", host: "10.207.203.216", path: "/AppWebservice/Service1.asmx/getNewsData")!
url = NSURL(string: "http://10.207.206.74/AppWebservice/Service1.asmx/getUniqDossier")!
// Call custom function.
loadRss(url);
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = ""
let backImg:UIImage! = UIImage(named: "backPicture.png")
self.navigationItem.backBarButtonItem =
UIBarButtonItem(image:backImg, style:.Plain, target:self, action:nil);
let navBgImage:UIImage = UIImage(named: "express.png")!
self.navigationController?.navigationBar.setBackgroundImage(navBgImage, forBarMetrics: .Default)
}
func loadRss(data: NSURL) {
let myParser = DossierParser(URL: data)
myFeed = myParser.feeds
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "openPage" {
let indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow!
let selectedFTitle: String = myFeed[indexPath.row].objectForKey("DosNum") as! String
let selectedFContent: String = myFeed[indexPath.row].objectForKey("Dossier_number") as! String
// Instance of our feedpageviewcontrolelr
let fpvc: FeedPageViewController = segue.destinationViewController as! FeedPageViewController
fpvc.selectedFeedTitle = selectedFTitle
fpvc.selectedFeedFeedContent = selectedFContent
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myFeed.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let chevron = UIImage(named: "Next4.png")
cell.accessoryType = .DisclosureIndicator
cell.accessoryView = UIImageView(image: chevron!)
cell.textLabel?.textColor = UIColor.blackColor()
// Feeds dictionary.
var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as! NSDictionary
// Set cell properties.
cell.textLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("DosNum") as? String
cell.detailTextLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("Date_text") as? String
return cell
}
I would appreciate any sort of help. My guessing there should be easier way around it, but I don't know it, so if someone has suggestion it would be nice!
Thanks!
I believe you would want to retain an instance of fCategory and pass it to the second parser class via init.
The second parser class should have the following to allow for the fcategory to be passed in and stored locally for use by the parser.
let fcategory = NSMutableString()
let URL = NSURL
init(URL: NSURL, category: String){
super.init()
self.URL = URL
self.fcategory = category
self.startParse(URL, fcategory)
}
I worked on my XML feed reader with a TableViewControllerand it was working perfectly but as it's not flexible, I wanted to move to another ViewController which includes `TableView'. However, even though I think I made the connections right (creating IBOutlet from tableview, using the right objects in custom cell in CustomCell class etc), it shows blank cells.
You can find the code below. I am using CustomCell class to create my custom cell. What am I missing here?
class originalViewController: UIViewController,UITableViewDelegate, NSXMLParserDelegate, UIScrollViewDelegate{
#IBOutlet var tableView: UITableView!
var parser = NSXMLParser()
var feeds = NSMutableArray()
var elements = NSMutableDictionary()
var element = NSString()
var ftitle = NSMutableString?()
var link = NSMutableString?()
var fdescription = NSMutableString?()
var fIMG = NSMutableString?()
var fAuthor = NSMutableString?()
var fDate = NSMutableString?()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
feeds = []
var url = NSURL(string: "http://www.marketoloji.com/?feed=rss2")
parser = NSXMLParser(contentsOfURL: url)!
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "openPage" {
var indexPath: NSIndexPath = self.tableView.indexPathForSelectedRow()!
let wvc: WebViewController = segue.destinationViewController as WebViewController
var selectedURL: String = feeds[indexPath.row].objectForKey("link") as String
selectedURL = selectedURL.stringByReplacingOccurrencesOfString(" ", withString: "")
selectedURL = selectedURL.stringByReplacingOccurrencesOfString("\n", withString: "")
wvc.selectedLink = selectedURL
}
}
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
element = elementName
if (element as NSString).isEqualToString("item"){
elements = NSMutableDictionary.alloc()
elements = [:]
ftitle = ""
link = ""
fdescription = ""
fAuthor = ""
fDate = ""
fIMG = ""
} else if element.isEqualToString("enclosure") {
var imgLink = attributeDict["url"] as String
imgLink = imgLink.stringByReplacingOccurrencesOfString(" ", withString: "")
imgLink = imgLink.stringByReplacingOccurrencesOfString("\n", withString: "")
fIMG?.appendString(imgLink)
println(imgLink)
}
}
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!){
if (elementName as NSString).isEqualToString("item"){
if ftitle != nil {
elements.setObject(ftitle!, forKey: "title")
}
if link != nil {
elements.setObject(link!, forKey: "link")
}
if fdescription != nil {
elements.setObject(fdescription!, forKey: "description")
}
if fAuthor != nil {
elements.setObject(fAuthor!, forKey: "creator")
}
if fDate != nil {
elements.setObject(fDate!, forKey: "date")
}
if fIMG != nil {
elements.setObject(fIMG!, forKey: "imageLink")
}
feeds.addObject(elements)
}
}
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
if element.isEqualToString("title") {
ftitle?.appendString(string)
} else if element.isEqualToString("link") {
link?.appendString(string)
} else if element.isEqualToString("description") {
fdescription?.appendString(string)
} else if element.isEqualToString("dc:creator") {
fAuthor?.appendString(string)
} else if element.isEqualToString("pubDate") {
fDate?.appendString(string)
}
}
func parserDidEndDocument(parser: NSXMLParser!) {
self.tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell") as CustomCell
let cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as CustomCell
cell.setCell(feeds.objectAtIndex(indexPath.row).objectForKey("title") as String, fDescription: feeds.objectAtIndex(indexPath.row).objectForKey("description") as String, fAuthor: feeds.objectAtIndex(indexPath.row).objectForKey("creator") as String, fDate: feeds.objectAtIndex(indexPath.row).objectForKey("date") as String, fImage: feeds.objectAtIndex(indexPath.row).objectForKey("imageLink") as String)
//cell.backgroundColor = UIColor.clearColor()
return cell
}
}
Figured out that I didnt connect the delegate and datasource of the table to the view controller, that was the main problem.