Creating a custom activity indicator in Swift allows you to tailor the appearance and behavior of your loading spinner to fit the style of your app. Here's a step-by-step guide to creating a simple custom activity indicator using UIView Step 1: Create a New Swift File for the Custom Activity Indicator Create a new Swift file and name it RotatingCirclesView.swift . Add the following code to define a custom UIView subclass for your activity indicator: // // RotatingCirclesView.swift // Welcome In // // Created by Praveen Kumar on 05/09/24. // import UIKit class RotatingCirclesView : UIView { let circle1 = UIView ( frame : CGRect ( x : 20 , y : 20 , width : 60 , height : 60 )) let circle2 = UIView ( frame : CGRect ( x : 120 , y : 20 , width : 60 , height : 60 )) let position : [ CGRect ] = [ CGRect ( x : 30 , y : 20 , width : 60 , height : 60 ), CGRect ( x : 60 , y : 15 ,...
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 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
var delegate: XMLParserDelegate?
A delegate object that receives messages about the parsing process.
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) {
}
}
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 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
- init?(contentsOf: URL) - Initializes a parser with the XML content referenced by the given URL.
- init(data: Data) - Initializes a parser with the XML contents encapsulated in a given data object.
- init(stream: InputStream) - Initializes a parser with the XML contents from the specified stream and parses it.
var delegate: XMLParserDelegate?
A delegate object that receives messages about the parsing process.
- func parser(XMLParser, didStartElement: String, namespaceURI: String?, qualifiedName: String?, attributes: [String : String] = [:]){}
- func parser(XMLParser, didEndElement: String, namespaceURI: String?, qualifiedName: String?){}
- func parser(XMLParser, foundCharacters: String){}
- func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
}
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
Post a Comment