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) {
}

}




Popular posts from this blog

How Create Animated Circle Progress Bar iOS 11 Swift 4

Animated Circle Progress Bar iOS 11 Swift 4


With MBCircularProgressBar - 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 MBCircularProgressBarView in StoryBoard. Open Atribute inspector and cu…