Property in Swift - Computed property | Property Observers (WillSet & DidSet)

   Computed property -  Computed properties are part of a property type in Swift.  Stored properties are the most common which save and return a stored value  Computed properties calculate (rather than store) a value. A computed property provides a getter and an optional setter to indirectly access other properties and values. Computed property in swift is an interesting topic as you can write code inside a property in swift. Computed properties are provided by classes, structures, and enumerations but stored properties are provided only by classes and structures. This computed property swift tutorial has some tips on how to use the computed property in the right way and avoid the common mistakes that swift programming beginners do while computed property. Example :- Computed property A Calculate Simple Intrest struct CalculateLoan {      var amount : Int      var rate : Int      var years : Int      var simpleInterest: Int {          get {              return ( amount * rate

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