Calculate age from birth date using Swift

Here is how to calculate age from birth date using Swift.

import UIKit

class _ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myDOB = NSCalendar.currentCalendar().dateWithEra(1, year: 1970, month: 09, day: 10, hour: 0, minute: 0, second: 0, nanosecond: 0)!
        let myAge = myDOB.age
        println(self.calculateAge(myDOB))
    }

    func calculateAge (birthday: NSDate) -> Int {
        return NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: birthday, toDate: NSDate(), options: nil).year
    }

}

extension NSDate {
    var age:Int {
        return NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: self, toDate: NSDate(), options: nil).year
    }
}

How to call REST APIs with AlamoFire and Swift

Alamofire is a networking API that leverages the full power of Swift.

Reference:
http://www.raywenderlich.com/85080/beginning-alamofire-tutorial
https://github.com/Alamofire/Alamofire

alamofire

alamofire

Here is sample how to call REST APIs with AlamoFire.

import UIKit
import Alamofire

class ViewController: ViewController {

    var user: [JSON] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "https://api.github.com/users/datomnurdin").responseJSON { (request, response, json, error) in
            if json != nil {
                var jsonObj = JSON(json!)
                if let data = jsonObj["user"].arrayValue as [JSON]?{
                    println(data)
                }
            }
        }
    }
}

Swift iOS Tutorial – Core Data – Add Update Delete

Core Data is an object graph and persistence framework provided by Apple in the Mac OS X and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0.

Reference: https://en.wikipedia.org/wiki/Core_Data

Core Data

Core Data

Here I show some useful core data queries below (before that you need to create a model):

import UIKit
import CoreData

@objc(Entityones)
class Entityones: NSManagedObject {

@NSManaged var attribute_one: String
@NSManaged var attribute_two: String
@NSManaged var attribute_three: String

}

Core Data queries.

Create/Add query

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        
        let context: NSManagedObjectContext = appDel.managedObjectContext!
        let en = NSEntityDescription.entityForName("Entityones", inManagedObjectContext: context)

        var newEn =  Entityones(entity: en!, insertIntoManagedObjectContext: context)
            
        newEn.attribute_one = "param1"
        newEn.attribute_two = "param2"
        newEn.attribute_three = "param3"
        
        context.save(nil)

Update query

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
                        let context: NSManagedObjectContext = appDel.managedObjectContext!
                        
                        let request = NSFetchRequest(entityName: "Entityones")
                        request.predicate = NSPredicate(format: "attribute1 = %@", "param1")
                        
                        if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(request, error: nil) as? [NSManagedObject] {
                            if fetchResults.count != 0{
                                
                                var managedObject = fetchResults[0]
                                managedObject.setValue("param1", forKey: "attribute_one")
                                managedObject.setValue("param2", forKey: "attribute_two")
                                managedObject.setValue("param3", forKey: "attribute_three")
                                
                                context.save(nil)
                             }
                        }

Delete query

//use on UITableView
var myList: Array <AnyObject> = []

let appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
            let context: NSManagedObjectContext = appDel.managedObjectContext!
            context.deleteObject(myList[indexPath.row] as! NSManagedObject)
            myList.removeAtIndex(indexPath.row)
            context.save(nil)

If you want know more details how to integrate these queries to your application, feel free to drop your email here, nurdinnorazanservices@gmail.com.

Develop a simple iOS mobile app (toDoList) using Swift – Part 1

Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.

swift programming language

swift programming language

Here are some of features:

  1. Modern
  2. Designed for Safety
  3. Fast and Powerful
  4. Interactive Playgrounds
  5. Ready Today
  6. Read-Eval-Print-Loop (REPL)

Reference: https://developer.apple.com/swift/

Getting Started.

Before we start this tutorial, make sure you already setup your machine (mac) with these tools:

  1. Xcode 6.3.2 GM seed – https://developer.apple.com/xcode/downloads/ (More stable than Xcode 6.3.1).

Open Xcode and create a new Single View Application. For product name, use RevivalxSwiftToDoList and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Single View Application

Single View Application

RevivalxSwiftToDoList

RevivalxSwiftToDoList

Install CocoaPods using terminal. What is CocoaPods?

CocoaPods manages library dependencies for your Xcode projects.

The dependencies for your projects are specified in a single text file called a Podfile. CocoaPods will resolve dependencies between libraries, fetch the resulting source code, then link it together in an Xcode workspace to build your project.

Ultimately the goal is to improve discoverability of, and engagement in, third party open-source libraries by creating a more centralised ecosystem.

Reference: https://guides.cocoapods.org/using/getting-started.html

Open your terminal and type this command.

sudo gem install cocoapods
sudo gem install cocoapods

sudo gem install cocoapods

Go to your directory and initialize your pod using this command.

cd /Users/MNurdin/Documents/iOS/RevivalxSwiftToDoList
pod init
pod init

pod init

Open your finder and edit pod file (Podfile) with these one.

# Uncomment this line to define a global platform for your project
#platform :ios, '8.0'
use_frameworks!

pod 'HanekeSwift'
pod 'Parse'
pod 'ParseFacebookUtils'
pod 'ParseUI'

target 'RevivalxSwiftToDoList' do

end

target 'RevivalxSwiftToDoListTests' do

end

The reasons why we need these libraries because

Go back to your terminal and run pod install to install all the dependencies. It takes a few of minutes to download.

pod install
Pod install.

Pod install.

After finish downloading, open RevivalxSwiftToDoList.xcworkspace file, not RevivalxSwiftToDoList.xcodeproj because we want to use the pod.

Storyboards and interface builder

Set to Compact Width | Any Height.

Compact Width | Any Height

Compact Width | Any Height

Delete ViewController.swift and ViewController on the Main.Storyboard. Drag a Table View Controller and View Controller to Main.Storyboard.

Main.Storyboard

Main.Storyboard

Select Table View Controller and navigate to Attributes inspector. Tick Is Initial View Controller.

Attributes inspector

Attributes inspector

Select the Table View Controller again and in the menu go to Editor > Embed In > Navigation Controller. This adds a Navigation Controller to the storyboard with an initial scene.

Editor > Embed In > Navigation Controller

Editor > Embed In > Navigation Controller

Select the Navigation Item under the Table View Controller, and in the Attributes Inspector type To Do List as the Title.

Navigation Item

Navigation Item

From the Object Library, drag a Bar Button Item to the right of the navigation bar on the Table View Controller. Select the Bar Button Item (which has a default value of “Item”) and in the Attributes Inspector, in the Identifier option, choose Add. This will change the button to the add symbol (+).

Bar Button Item

Bar Button Item

Select the Table View Controller, press control button and drag to View Controller like image below. We added a segue.

Segue

Segue

Name it MySegue in Show the Attributes Inspector > Identifier.

Storyboard Segue

Storyboard Segue

Result

Main.Storyboard

Main.Storyboard

Continue on next post, http://blog.revivalx.com/2015/08/12/develop-a-simple-ios-mobile-app-todolist-using-swift-part-2/.