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:
[code language=”obj-c”]
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)
[/code]
Parse the JSON by finding your key:
[code language=”obj-c”]
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)")
}
}
[/code]
Complete code snippet with UITableView:
[code language=”obj-c”]
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])
}
}
[/code]
Helping, Learning, Coding 🙂

Working with Alert in Swift Language – iOS 8 – Xcode 6

Alert View
Alert View

In iOS 8 the UIAlertView is deprecated. Now UIAlertController is a single class for creating and interacting with what we knew as UIAlertView.
We have to create alert as follows.
[code language=”obj-c”]
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
[/code]
We can also create handler for handle the events on alert.
[code language=”obj-c”]
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
switch action.style{
case .Default:
println("default")
break
case .Cancel:
println("cancel")
break
case .Destructive:
println("destructive")
break
}
}))
self.presentViewController(alert, animated: true, completion: nil)
[/code]
Happy Coding 🙂
For more iOS tutorials visit iTuts.

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 🙂