How to use Alamofire and SwiftyJSON with Swift? – Swift 3 – iOS 10 – Xcode 8

Swift JSON
Swift JSON

Alamofire is an HTTP networking library written in Swift.
SwiftyJSON makes it easy to deal with JSON data in Swift.

Read more

Realm – mobile database with Swift

What is Realm?
Realm is a mobile database
Realm is a replacement for SQLite & Core Data.
It can save you thousands of lines of code & weeks of work,
and lets you craft amazing new user experiences.

Download the Realm framework for swift from https://realm.io/
[code language=”obj-c”]
import UIKit
import RealmSwift
class Person: Object {
dynamic var name = ""
dynamic var age = 0
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Initializing the object
let personObj1 = Person()
personObj1.name = "Ashish"
personObj1.age = 25
println("name of person : \(personObj1.name)")
// Writing it to realm
let realm = Realm()
realm.write {
realm.add(personObj1)
}
let personObj2 = Person()
personObj2.name = "Darshak"
personObj2.age = 27
realm.write {
realm.add(personObj2)
}
// Quering
let r = Realm().objects(Person).filter("age > 24")
println(r)
// Queries are chainable
let r2 = r.filter("name contains ‘Ashish’")
println(r2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
[/code]
Output :
[code language=”obj-c”]
name of person : Ashish
Results<Person> (
[0] Person {
name = Ashish;
age = 25;
},
[1] Person {
name = Darshak;
age = 27;
}
)
Results<Person> (
[0] Person {
name = Ashish;
age = 25;
}
)
[/code]
Happy Coding 🙂

Passing data with Unwind Segue in Swift Language – iOS 8

Unwind Segue Data
Unwind Segue Data

We have learn about Work with Unwind Segue in Swift Language – iOS 8 in first tutorial. Now we will learn how to pass the data with unwind segue.

It just simple.
Continue with the same example project.
Take data variables which you want to get in the parent view.
For example,
[code language=”obj-c”]
class ViewController2: UIViewController {
var data:String = "view 2 data"
….
}
[/code]

To get data from first view controller we have to get data from source view controller like follows :

[code language=”obj-c”]
@IBAction func unwindToVC(segue:UIStoryboardSegue) {
if(segue.sourceViewController .isKindOfClass(ViewController2))
{
var view2:ViewController2 = segue.sourceViewController as ViewController2
let alert = UIAlertView()
alert.title = "UnwindSegue Data"
alert.message = view2.data
alert.addButtonWithTitle("Ok")
alert.show()
}
if(segue.sourceViewController .isKindOfClass(ViewController3))
{
var view3:ViewController3 = segue.sourceViewController as ViewController3
let alert = UIAlertView()
alert.title = "UnwindSegue Data"
alert.message = view3.data
alert.addButtonWithTitle("Ok")
alert.show()
}
}
[/code]
Download project with this stuff UnwindSegueData.zip
Thanks!
Happy Coding 😀

Work with Unwind Segue in Swift Language – iOS 8

Unwind - Exit
Unwind – Exit

An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. “go back” multiple steps in your navigation hierarchy with a single unwind action.

To enable the Unwind Segue you need to add some code first.
[code language=”obj-c”]
@IBAction func unwindToVC(segue: UIStoryboardSegue) {
}
[/code]
You have to add this code in the view controller where you want to unwind (came back).

Unwind To View
Unwind To View

Suppose you want to came back from second or third view to first view then you have to add the code in first view.
Then just connect any control(Which contains action) with the unwind segue.
Unwind Segue
Unwind Segue

For check the particular view controller by unwind segue, use following code :
[code language=”obj-c”]
@IBAction func unwindToVC(segue:UIStoryboardSegue) {
if(segue.sourceViewController .isKindOfClass(ViewController2))
{
let alert = UIAlertView()
alert.title = "UnwindSegue"
alert.message = "Unwind from view 2"
alert.addButtonWithTitle("Ok")
alert.show()
}
if(segue.sourceViewController .isKindOfClass(ViewController3))
{
let alert = UIAlertView()
alert.title = "UnwindSegue"
alert.message = "Unwind from view 3"
alert.addButtonWithTitle("Ok")
alert.show()
}
}
[/code]
Download project with this stuff UnwindSegue.zip
In next tutorial you will find the topic Passing data with Unwind Segue in Swift Language – iOS 8
Thanks!
Happy Coding 😀

Google Place Autocomplete View With Swift Language through Alamofire networking library

Google Place Autocomplete
Google Place Autocomplete

Add the Alamofire CocoaPods in your swift project.
alamofire
alamofire

Find your Google place API key on Google APIs Console.
GOOGLE PLACE API KEY
GOOGLE PLACE API KEY

ViewConroller.swift
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let gpaViewController = GooglePlacesAutocomplete(
apiKey: "YOUR API KEY",
placeType: .Address
)
gpaViewController.placeDelegate = self
presentViewController(gpaViewController, animated: true, completion: nil)
}
}
extension ViewController: GooglePlacesAutocompleteDelegate {
func placeSelected(place: Place) {
println(place.description)
}
func placeViewClosed() {
dismissViewControllerAnimated(true, completion: nil)
}
}
[/code]
GooglePlacesAutocomplete.xib
GooglePlacesAutocomplete.xib
GooglePlacesAutocomplete.xib

GooglePlacesAutocomplete.swift
[code language=”obj-c”]
import UIKit
import Alamofire
enum PlaceType: Printable {
case All
case Geocode
case Address
case Establishment
case Regions
case Cities
var description : String {
switch self {
case .All: return ""
case .Geocode: return "geocode"
case .Address: return "address"
case .Establishment: return "establishment"
case .Regions: return "regions"
case .Cities: return "cities"
}
}
}
struct Place {
let id: String
let description: String
}
protocol GooglePlacesAutocompleteDelegate {
func placeSelected(place: Place)
func placeViewClosed()
}
// MARK: – GooglePlacesAutocomplete
class GooglePlacesAutocomplete: UINavigationController {
var gpaViewController: GooglePlacesAutocompleteContainer?
var placeDelegate: GooglePlacesAutocompleteDelegate? {
get { return gpaViewController?.delegate }
set { gpaViewController?.delegate = newValue }
}
convenience init(apiKey: String, placeType: PlaceType = .All) {
let gpaViewController = GooglePlacesAutocompleteContainer(
apiKey: apiKey,
placeType: placeType
)
self.init(rootViewController: gpaViewController)
self.gpaViewController = gpaViewController
let closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "close")
gpaViewController.navigationItem.leftBarButtonItem = closeButton
gpaViewController.navigationItem.title = "Enter Address"
}
func close() {
placeDelegate?.placeViewClosed()
}
}
// MARK: – GooglePlaceSearchDisplayController
class GooglePlaceSearchDisplayController: UISearchDisplayController {
override func setActive(visible: Bool, animated: Bool) {
if active == visible { return }
searchContentsController.navigationController?.navigationBarHidden = true
super.setActive(visible, animated: animated)
searchContentsController.navigationController?.navigationBarHidden = false
if visible {
searchBar.becomeFirstResponder()
} else {
searchBar.resignFirstResponder()
}
}
}
// MARK: – GooglePlacesAutocompleteContainer
class GooglePlacesAutocompleteContainer: UIViewController {
var delegate: GooglePlacesAutocompleteDelegate?
var apiKey: String?
var places = [Place]()
var placeType: PlaceType = .All
convenience init(apiKey: String, placeType: PlaceType = .All) {
self.init(nibName: "GooglePlacesAutocomplete", bundle: nil)
self.apiKey = apiKey
self.placeType = placeType
}
override func viewDidLoad() {
super.viewDidLoad()
let tv: UITableView? = searchDisplayController?.searchResultsTableView
tv?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
}
// MARK: – GooglePlacesAutocompleteContainer (UITableViewDataSource / UITableViewDelegate)
extension GooglePlacesAutocompleteContainer: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.searchDisplayController?.searchResultsTableView?.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
// Get the corresponding candy from our candies array
let place = self.places[indexPath.row]
// Configure the cell
cell.textLabel.text = place.description
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.placeSelected(self.places[indexPath.row])
}
}
// MARK: – GooglePlacesAutocompleteContainer (UISearchDisplayDelegate)
extension GooglePlacesAutocompleteContainer: UISearchDisplayDelegate {
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
getPlaces(searchString)
return false
}
private func getPlaces(searchString: String) {
Alamofire.request(.GET,
"https://maps.googleapis.com/maps/api/place/autocomplete/json",
parameters: [
"input": searchString,
"type": "(\(placeType.description))",
"key": apiKey ?? ""
]).responseJSON { request, response, json, error in
if let response = json as? NSDictionary {
if let predictions = response["predictions"] as? Array<AnyObject> {
self.places = predictions.map { (prediction: AnyObject) -> Place in
return Place(
id: prediction["id"] as String,
description: prediction["description"] as String
)
}
}
}
self.searchDisplayController?.searchResultsTableView?.reloadData()
}
}
}
[/code]
I have learned this thing from Howard Wilson’s(watsonbox) Github Repository : watsonbox/ios_google_places_autocomplete
Happy coding 🙂

Requesting Access to the Address Book – Swift Language – iOS 8

Request to Access Address Book
Request to Access Address Book

Here is simple steps to requesting access to the Address Book in Swift Language iOS 8
Import the framework of Address Book:
[code language=”objc”]
import AddressBook
[/code]
Create an object of Address Book:
[code language=”objc”]
var addressBook: ABAddressBookRef?
[/code]
Create a method for assigning the value to addressBook:
[code language=”objc”]
func createAddressBook(){
var error: Unmanaged<CFError>?
addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
}
[/code]
Post following code to requesting access:
[code language=”objc”]
switch ABAddressBookGetAuthorizationStatus(){
case .Authorized:
println("Already authorized")
createAddressBook()
/* Access the address book */
case .Denied:
println("Denied access to address book")
case .NotDetermined:
createAddressBook()
if let theBook: ABAddressBookRef = addressBook{
ABAddressBookRequestAccessWithCompletion(theBook,
{(granted: Bool, error: CFError!) in
if granted{
println("Access granted")
} else {
println("Access not granted")
}
})
}
case .Restricted:
println("Access restricted")
default:
println("Other Problem")
}
[/code]
Happy Coding 🙂

How to add an Objective-C file in your Swift Project? or How to set Objective-C bridging header?

Bridging header
Bridging header

To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add an Objective-C file to an existing Swift app.

If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding “-Bridging-Header.h”.

Alternatively, you can create a bridging header yourself by choosing File > New > File > (iOS or OS X) > Source > Header File.

You’ll need to edit the bridging header file to expose your Objective-C code to your Swift code.

To import Objective-C code into Swift from the same target

  1. In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift.
    For example:
    [code language=”obj-c”]
    #import "XYZCustomCell.h"
    #import "XYZCustomView.h"
    #import "XYZCustomViewController.h"
    [/code]
  2. Under Build Settings, make sure the Objective-C Bridging Header build setting under Swift Compiler – Code Generation has a path to the header.

    The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.

Any public Objective-C headers listed in this bridging header file will be visible to Swift. The Objective-C functionality will be available in any Swift file within that target automatically, without any import statements. Use your custom Objective-C code with the same Swift syntax you use with system classes.

For Example:
[code language=”obj-c”]
let myCell = XYZCustomCell()
myCell.subtitle = "A custom cell"
[/code]
Helping, Learning, Coding 🙂
Source : Apple Documents

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
[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 🙂