Update : JSON Array Parsing in Swift Language – Swift 3 – iOS 10 – Xcode 8

Swift JSON
Swift JSON

So, how to parse following type of JSON?

Create JSON Array Object :

Parse JSON Array Object :

Complete code snippet with UITableView:

Posted a gist on github.

Helping, Learning, Coding 🙂

Add Launch Screen (LaunchImage) for iPhone 6 | 6 Plus in Xcode 6 | iOS 8

Hello Developers,
Greetings for iPhone 6, 6 Plus and Xcode 6 GM Seed !!

Question is how to add launch screens for iPhone 6 and 6 Plus.

iPhone 6 Launchscreen
iPhone 6 Launchscreen

As per Apple’s Guidelines create the launch screens :

For iPhone 6: 750 x 1334 Pixels Resolution
For iPhone 6 Plus: 1242 x 2208 Pixels Resolution

You have two options :

    1. Create launch screen by LaunchScreen.xib.
Launchscreen.xib settings
Launchscreen.xib settings
    1. Add Launch Images in assets folder.
Launch Image Assets
Launch Image Assets

Finally set the Launch Screen Settings :

Launchscreen Settings
Launchscreen Settings

Happy Screening 😉

Helping, Learning, Coding 🙂

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

var parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self

Delegate your class with XMLParserDelegate

class ViewController: UIViewController,XMLParserDelegate {
}

Add Delegate methods

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

Parse the XML with following method

parser.parse()

Complete sample code:

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 Demo on My Github. Both Swift 2.2 and Swift 3 versions are available.

Helping, Learning, Coding 🙂

JSON Parsing in Swift Language – iOS 8

Here is tutorial about parsing JSON in Swift Language iOS 8

Swift JSON
Swift JSON

Create a Dictionary of all JSON data:

        let url=NSURL(string:"http://api.androidhive.info/contacts/")
        let allContactsData=NSData(contentsOfURL:url)
        var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>

        NSLog("%@", allContacts)

Parse the JSON by finding your key:

        let contacts : AnyObject? = allContacts["contacts"]

        for contacts in allContacts.keys {
            println("All = \(contacts)")
            let contact : AnyObject? = allContacts[contacts]
            let collection = contact! as Array<Dictionary<String, AnyObject>>
            for subContact in collection {
                let name : AnyObject? = subContact["name"]
                let email : AnyObject? = subContact["email"]

                names+=name! as String
                emails+=email! as String

                println("Name: \(name)")
                println("Email: \(email)")
            }
        }

Complete code snippet with UITableView:

import UIKit

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{

    @IBOutlet var tblJson : UITableView = nil

    var names: String[] = []
    var emails: String[] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let url=NSURL(string:"http://api.androidhive.info/contacts/")
        let allContactsData=NSData(contentsOfURL:url)
        var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>

        NSLog("%@", allContacts)

        let contacts : AnyObject? = allContacts["contacts"]

        for contacts in allContacts.keys {
            println("All = \(contacts)")
            let contact : AnyObject? = allContacts[contacts]
            let collection = contact! as Array<Dictionary<String, AnyObject>>
            for subContact in collection {
                let name : AnyObject? = subContact["name"]
                let email : AnyObject? = subContact["email"]

                names+=name! as String
                emails+=email! as String

                println("Name: \(name)")
                println("Email: \(email)")
            }
        }

        println(names)
        println(emails)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.names.count;
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

        var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell

        if !cell {
            cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
        }
        cell!.textLabel.text = self.names[indexPath.row]
        cell!.detailTextLabel.text = self.emails[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected name : "+names[indexPath.row])
    }
}

Helping, Learning, Coding 🙂

Create Simple Table (UITableView) in Swift Language iOS8

Here is simple tutorial to create table (UITableView) in Swift Language – iOS 8 – Xcode 6

Swift Table
Swift Table

Attach your UITableView IBOutlet to .swift file

    @IBOutlet var tblSwift : UITableView = nil

Delegate UITableViewDelegate and UITableViewDataSource to your Controller

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
...
}

Don’t forgot to add the delegate methods otherwise you got error

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        ...
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        ...
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        ...
    }
}

Register your cell

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tblSwift.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        // Do any additional setup after loading the view, typically from a nib.
    }

Following is sample of complete code

import UIKit

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{

    @IBOutlet var tblSwift : UITableView = nil

    var items: String[] = ["This", "is" , "swift" , "language" , ":)"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tblSwift.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count;
    }

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        var cell:UITableViewCell = self.tblSwift.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel.text = self.items[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("You selected item "+items[indexPath.row]) //or
        println("You selected item \(items[indexPath.row])") //or
        println("You selected cell #\(indexPath.row)!")
    }
}

Helping, Learning, Coding 🙂