XML Parsing using NSXMLParser in Swift

Posted on Posted in iOS

For your reference, you can download the complete Xcode project from GitHub.

Steps:

(1) Create Swift Project

(2) Declare Variables in ViewController.swift file :

Now, declare some variables which we want to parse from XML file or Used in our Project. For variable declare in Swift Programming write below code :

(3) Implement NSXMLParser Delegate & import it’s method :

import UIKit
class ViewController: UIViewController, NSXMLParserDelegate, UITableViewDelegate, UITableViewDataSource
{
}
Now, write method of NSXMLParserDelegate methods, which looks like :
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject])
{
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
}
func parser(parser: NSXMLParser, foundCharacters string: String?)
{
}

(4) Create function startParsing() :

func startParsing()
{
    objPostArray = []
    objNSXMLParser = NSXMLParser(contentsOfURL: NSURL(string: “http://images.apple.com/main/rss/hotnews/hotnews.rss”))!
    objNSXMLParser.delegate = self
    objNSXMLParser.parse()
    tblNews.reloadData()
}

5) Retrieve data from XML file using Delegate Method :

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject])
{
     objDataString = elementName
     if (elementName as NSString).isEqualToString(“item”) {
          objPostDictionary = NSMutableDictionary.alloc()
          objPostDictionary = [:]
          objDataTitle = NSMutableString.alloc()
          objDataTitle = “”
          objDataDate = NSMutableString.alloc()
          objDataDate = “”
      }
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
     if (elementName as NSString).isEqualToString(“item”) {
          if !objDataTitle.isEqual(NSNull) {
               objPostDictionary.setObject(objDataTitle, forKey: “title”)
          }
          if !objDataDate.isEqual(NSNull) {
               objPostDictionary.setObject(objDataDate, forKey: “date”)
          }
          objPostArray.addObject(objPostDictionary)
      }
}
func parser(parser: NSXMLParser, foundCharacters string: String?)
{
     if objDataString.isEqualToString(“title”) {
          objDataTitle.appendString(string!)
     } else if objDataString.isEqualToString(“pubDate”) {
          objDataDate.appendString(string!)
     }
}
Display Data
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
     return objPostArray.count
}
    
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
     var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(“Cell”) as! UITableViewCell
    
     if(cell == nil) {
          cell = NSBundle.mainBundle().loadNibNamed(“Cell”, owner: self, options: nil)[0] as! UITableViewCell;
     }
     cell.textLabel?.text = objPostArray.objectAtIndex(indexPath.row).valueForKey(“title”) as! NSString as String
     cell.detailTextLabel?.text = objPostArray.objectAtIndex(indexPath.row).valueForKey(“date”) as! NSString as String
        
     return cell as UITableViewCell
}
For your reference, you can download the complete Xcode project from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *