Skip to main content

XML Parsing Web Service with Custom Objects Parameter in iOS With Swift - Tutorial

XML Parsing Web Service or Custom Objects Parameter in iOS With Swift - Example

What is XML? or How to Read XML Files From the WebXML is a text file with special opening and closing tags. Most of these tags look like HTML, however there’s a difference: there are no reserved tags. Parse a simple XML document from URL and convert it into objects. The author makes up whatever tags they want. For example this is properly formed XML-

XML Parsing


<?xml version="1.0"?>
<catalog>
    <book id="1">
        <title>To Kill a Mockingbird</title>
        <author>Harper Lee</author>
    </book>
    <book id="2">
        <title>1984</title>
        <author>George Orwell</author>
    </book>
    <book id="3">
        <title>The Lord of the Rings</title>
        <author>J.R.R Tolkien</author>
    </book>
    <book id="4">
        <title>The Catcher in the Rye</title>
        <author>J.D. Salinger</author>
    </book>
    <book id="5">
        <title>The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>
    </book>
</catalog>

An XMLParser notifies its delegate about the items (elements, attributes, CDATA blocks, comments, and so on) that it encounters as it processes an XML document.

Three Type Initializing a Parser Object

  1. init?(contentsOf: URL) - Initializes a parser with the XML content referenced by the given URL.
  2.  init(data: Data) - Initializes a parser with the XML contents encapsulated in a given data object.
  3.  init(stream: InputStream) - Initializes a parser with the XML contents from the specified stream and parses it.
Managing Delegates with

var delegate: XMLParserDelegate?
A delegate object that receives messages about the parsing process.

  1. func parser(XMLParser, didStartElement: String, namespaceURI: String?, qualifiedName: String?, attributes: [String : String] = [:]){}
  2. func parser(XMLParser, didEndElement: String, namespaceURI: String?, qualifiedName: String?){}
  3. func parser(XMLParser, foundCharacters: String){}
  4. func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
    }
Example:- XML Parsing Web Servic

import UIKit

class ViewController: UIViewController, XMLParserDelegate {

    var ipAddr:String = ""
    var countryCode:String = ""
    var countryName:String = ""
    var latitude:String = ""
    var longitude:String = ""
    var currentParsingElement:String = ""
   
    @IBOutlet weak var ipAddressLabel:UILabel!
    @IBOutlet weak var countryCodeLabel:UILabel!
    @IBOutlet weak var countryNameLabel:UILabel!
    @IBOutlet weak var latitudeLabel:UILabel!
    @IBOutlet weak var longitudeLabel:UILabel!
   
override func viewDidLoad() {
        super.viewDidLoad()
        getXMLDataFromServer()
    }
  func getXmlDataFromServer(){

      let url = NSURL(string:"https://freegeoip.net/xml/4.2.2.2")
      let task = URLSession.shared.dataTask(with: url! as URL){ (data, response, eroor) in
      if data == nil{
      print("dataTaskWithRequest error: \(String(describing: error?.localizedDescription))")
      return
          }
      let parser = XMLParser(data: data!)
      parser.delegate = self
      parser.parse()
      }
      task.resume()
}

 func displayOnUI(){

        ipAddressLabel.text = ipAddr
        countryCodeLabel.text = countryCode
        countryNameLabel.text = countryName
        latitudeLabel.text = latitude
        longitudeLabel.text = longitude
    }

func parser(_parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:])
{
       currentParsingElement = elementName
       if elementName = "Response"{
       print("starting Parsing")
        }
    }

func parser(_parser: XMLParser, foundCharacters string: String){
       let foundChar = string.trimmingCharacters(in: NSCharacterSet.whilespacesAndNewLines)
       if(!foundChar.isEmpty){
       if currentParsingElement == "IP"{
       ipAddr += foundChar
    }
       else if currentParsingElement == "CountryCode"{
       countryCode += foundChar
}
       else if currentParsingElement == "CountryName"{
       countryName += foundChar
}
       else if currentParsingElement == "Latitude"{
        latitude += foundChar
}
       else if currentParsingElement == "Longitude"{
        longitude += foundChar
  }
}
func parser(_parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){
       if elementName = "Response"{

       print("Ended Parsing")
  }
}
func parserDidEndDocument(_parser: XMLParser){
       DispatchQueue.main.async{
      // Update UI
      self.displayOnUI()
    }
}
func parser(_parser: XMLParser, parseErrorOccured parseError: Error){
       print("parseErrorOccured: \(parseError)")
  }
}

Example:- XML Parsing Custom Object

NSObject Class

class House: NSObject {
    var id:Int = 0
    var name:String = ""
    var location:String = ""
}

ViewController

import UIKit

class ViewController: UIViewController, XMLParserDelegate {

var housearray = [House]()
var parser = XMLParser()
override func viewDidLoad() {
 super.viewDidLoad()

     let urlString = URL(string: "http://url/file.php?parameter=value")
     self.parser = XMLParser(contentsOf: urlString!)!
     self.parser.delegate = self
     let success:Bool = self.parser.parse()
 if success {
      print("success")
 } else {
      print("parse failure!")
  }
 }

 func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
 if(elementName=="House")
        {
            let house = House()
            for string in attributeDict {
                let strvalue = string.value as NSString
                switch string.key {
                  case "id":
                    house.id = strvalue.integerValue
                    break
                  case "name":
                    house.name = strvalue as String
                    break
                  case "location":
                    house.location = strvalue as String
                    break
                  default:
                    break
                }
            }
            housearray.append(house)
        }
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName = "House"{

       print("Ended Parsing")
  }
}
func parser(_ parser: XMLParser, foundCharacters string: String) {

}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
}

}




Comments

Popular posts from this blog

Add a Scene Delegate to your existing project with Storyboard in Swift

To add a scene delegate, first, create a new Swift file that you’ll call "SceneDelegate" containing a subclass of UIResponder, just like the AppDelegate, and that conforms to UIWindowSceneDelegate.  As your app might supports other versions than iOS 13, make this class only available for iOS 13. This is what you should have : If you are working a project that is storyboard based, please set storyboard  initial view controller SceneDelegate.swift import UIKit @available ( iOS 13.0 , *) class SceneDelegate : UIResponder , UIWindowSceneDelegate {     var window : UIWindow ?     func scene ( _ scene: UIScene , willConnectTo session: UISceneSession , options connectionOptions: UIScene . ConnectionOptions ) {                  let storyboard = UIStoryboard (name: "Main" , bundle: nil )         let initialViewController = storyboard. instantiateViewController (withIdentifier: "ViewController" )         let mainNavigationController = UINavigationControlle

How Create Animated Circle Progress Bar iOS 11 Swift 4

  Animated Circle Progress Bar iOS 11 Swift 4 With MBCircularProgressBa r - https://github.com/MatiBot/MBCircularProgressBar A circular, animatable & highly customizable progress bar from the Interface Builder Swift, Using pod fite MBCircularProgressBar Installation Cocoapods terminal. pod "MBCircularProgressBar" That - A Simple Steps to installed pod file -        Open terminal        Command on terminal go to project folder Cd path        set your project path on terminal.        command : pod init        open pod file - open -e podfile        added in pod file with in : pod "MBCircularProgressBar"        Command : Pod install        Close project of Xcode        open your Project from terminals        Command : open PodDemos.xcworkspace After opern StoryBoard and Now drag a UIView over the viewController in storyboard Or set UIView Constraint width, height or verticle or horzentail space and set a class MBCircul

How to Use Multiple Sections in UITableView iOS Swift !

Multiple sections in UITableView iOS Swift. UITableView is very important part of iOS ecosystem. So we split tableviews in sections. Then its easier to find right information.  1. First let’s create a project as usual. Create a new single view application X code project. Set project name to UIViewController.  2. Go to main storyboard & select view controller & use UITableView 3. Select tableview & make it initial view controller  4 Create a custom Sections Class like Name => TableSections, create register cell static return “ getCellNibs ” method. Then create  4 section enum “TableItems” then after append all sections to an array model. import UIKit struct CellNib {      static func getCellNibs () -> [ String ] {          return [ "Cell1" , "Cell2" , "Cell3" , "Cell4" ]     } } enum TableItems : Int {      case TableSections1      case TableSections2      case TableSections3      case TableSections4 } class TableSec