XML Parsing in Swift Language – iOS 10 – XMLParser

XML Parsing in Swift Language
XML Parsing in Swift Language

Code syntax is changed in version Swift 3. So, I have updated this article with Xcode 8 – iOS 10

Here is tutorial about how to parse the XML data in Swift Language – iOS 10 – XMLParser
Start with creating object of XMLParser
[code language=”obj-c”]
var parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self
[/code]
Delegate your class with XMLParserDelegate
[code language=”obj-c”]
class ViewController: UIViewController,XMLParserDelegate {
}
[/code]
Add Delegate methods
[code language=”obj-c”]
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
}
[/code]
Parse the XML with following method
[code language=”obj-c”]
parser.parse()
[/code]
Complete sample code:
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController,XMLParserDelegate {
var strXMLData:String = ""
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var parser = XMLParser()
@IBOutlet var lblNameData : UILabel! = nil
override func viewDidLoad() {
super.viewDidLoad()
let url:String="http://api.androidhive.info/pizza/?format=xml"
let urlToSend: URL = URL(string: url)!
// Parse the XML
parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse success!")
print(strXMLData)
lblNameData.text=strXMLData
} else {
print("parse failure!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=true;
}
passData=true;
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement="";
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=false;
}
passData=false;
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if(passName){
strXMLData=strXMLData+"\n\n"+string
}
if(passData)
{
print(string)
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("failure error: ", parseError)
}
}
[/code]
Code Demo on My Github. Both Swift 2.2 and Swift 3 versions are available.
Helping, Learning, Coding 🙂

Create a application in Xcode 6 – iOS 8 without storyborard in Swift language and work with controls

Xcode6  Swift  iOS8
Xcode6 Swift iOS8

We can create navigation-based application without storyboard in Xcode 6 (iOS 8) like as follows:

  • Create an empty application by selecting the project language as Swift.
  • Add new cocoa touch class files with the interface xib. (eg. TestViewController)
  • In the swift we have only one file interact with the xib i.e. *.swift file, there is no .h and .m files.
  • We can connect the controls of xib with swift file same as in iOS 7.

Following are some snippets for work with the controls and Swift !
[code lang=”obj-c”]
//
// TestViewController.swift
//
import UIKit
class TestViewController: UIViewController {
@IBOutlet var testBtn : UIButton
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
@IBAction func testActionOnBtn(sender : UIButton) {
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert’s cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
[/code]
Changes in AppDelegate.swift file
[code lang=”obj-c”]
//
// AppDelegate.swift
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController = UINavigationController(rootViewController: testController)
self.window!.rootViewController = self.navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
[/code]
Happy Coding 🙂