Saturday, December 9, 2017

Contacts Framework in iOS

Apple provides ContactsUI framework for displaying and selecting the contacts. It fetches all the contacts from the iPhone's Contact App. Let's fire up the Xcode and create the project.


We're going to create a simple app for showing contact list and selecting the contacts then display it in label. ContactUI framework have a controller called CNContactPickerViewController which shows the contact lists.

Steps

  • Open ViewController.swift file and import ContactsUI
  • Add CNContactPickerDelegate in ViewController
  • Drag and drop the button, label in the View from Object Library for displaying contact
  • Then create an @IBOutlet variable for label and @IBAction function for button in ViewController.

import UIKit
import ContactsUI

class ViewController: UIViewController, CNContactPickerDelegate {
    
    @IBOutlet weak var numberLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

  • Then add the below code for displaying and cancelling the contact view controller. 

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        
        contacts.forEach { contact in
            for data in contact.phoneNumbers {
                let phoneNumber = data.value
                print("Your phone number is \(phoneNumber)")
                numberLabel.text = phoneNumber.stringValue
            }
        }
    }
    
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        
        print("Cancelled the contact picker view controller")
    }

  • contactPicker(_, didSelect) execute when you're selecting the contacts from the contact view controller. After clicking the done button, you can easily retrieve the contacts from contacts array, then we're assigning the contact number for Label
  • contactPickerDidCancel(_ ) function is called when you're clicking the cancel button in contact view controller.

Full Code :

//
//  ViewController.swift
//  Contact List
//
//  Created by Vinoth Vino on 09/12/17.
//  Copyright © 2017 Vinoth Vino. All rights reserved.
//

import UIKit
import ContactsUI

class ViewController: UIViewController, CNContactPickerDelegate {
    
    @IBOutlet weak var numberLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    @IBAction func showContacts(_ sender: Any) {
        
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        present(contactPicker, animated: true, completion: nil)
    }
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        
        contacts.forEach { contact in
            for data in contact.phoneNumbers {
                let phoneNumber = data.value
                print("Your phone number is \(phoneNumber)")
                numberLabel.text = phoneNumber.stringValue
            }
        }
    }
    
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        
        print("Cancelled the contact picker view controller")
    }
}


Download:https://github.com/vinothvino42/CoderEarthExampleCodes.git

Output :









I hope you guys now understand how to fetch contacts in iOS. See you in the next tutorial..

Happy Coding 💻








Monday, May 15, 2017

Store Data Permanently using UserDefaults

       Hello developers, In this tutorial we're going to learn how to store user's phone number in iOS Apps using UserDefaults(NSUserDefaults) class. If you tried to store huge amount of data using UserDefaults then it'll slow down your app.


What is UserDefaults ?


        For storing a user preference, we want to use UserDefaults this will allow you to store a small amount of datas such as users phone number, user email id and so on. UserDefault can be used to store integers, double, string, booleans, arrays, dictionaries etc. At runtime, it'll read the defaults that your application uses from a user's default database.

        You may noticed in any social messaging app that once you entered the username for the first time then it'll show you again and again when each time the app launches. Okay let's fire up the Xcode and start building our app from scratch.

Creating a Project


  • Open Xcode and Create a new project from the file menu.
  • Select Single View Application template and click Next.
  • Give name to product, organization and organization identifier. See below image for reference.

   

Adding Views 


  • Click the Main.Storyboard file.
  • Drag and drop the Labels, TextField and Buttons from the Object Library into the View. Do like below image.

  • Now open the Assistant Editor in Xcode. Click the double circled icon in top right corner(See the image below) or Click CMD + OPTION + ENTER shortcut.



  • Then drag and drop the labels, textField and buttons into the view controller(viewcontroller.swift file)



  • Then it'll show you one tiny window, in that you've to change the connections and click connect. For button, change the connection from Outlet into Action. For Label, set the connection as Outlets(By default, it's Outlet only). 
  • Note: Here I took screenshots only for label and buttons. So just do the same procedure for textField also and set the connection as Outlet



View Controller Code


    @IBOutlet var phoneNumbLabel: UILabel!
    @IBOutlet var textField: UITextField!
    
    @IBAction func saveBtn(_ sender: Any) {
        
        let phNumb = textField?.text
        
        //Storing phone numbers with userphnumb key
        UserDefaults.standard.set(phNumb, forKey: "userphnumb")
        
        //Retrieving phone numbers from user default database with userphnumb key and it cast it into String because we need to set it as label in our app
        if let retrievedNumb = UserDefaults.standard.object(forKey: "userphnumb") as? String{
            
             print(retrievedNumb)
             phoneNumbLabel.text = retrievedNumb
            
        }
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let retrievedVal = UserDefaults.standard.object(forKey: "userphnumb") as? String{
            
            phoneNumbLabel.text = retrievedVal
            
        }
    }



Run the App


      Now build the project and run it. Then the app will open in Simulator.



    In the first time of installation you'll have "Label" text in the right side of "Your number:". Just type the phone number and click the save button(it'll stored in the database) then the "Label" is changed to number what you've typed in the TextField. Then if you close the app and open it again then you'll have your number. Our app fetches the data from the database with the key and it shows to you in the right side of "Your number". This is what the beauty of User Defaults :)

Download this Project

    Guys, I hope you understand about the UserDefaults in Swift. If you have any doubts in this tutorial then just drop your comments right below the post. See you in the next tutorial..

    Happy Coding :)

iOS Multiple View Controller

In this tutorial, I'm gonna show you how to create a multiple view controller and segue between the view controllers.


What is View ?


    View(UIView) class is a rectangular area on the screen. It is attached to the UIWindows and it draws their content. You've seen these views in all apps for sure. Let me tell you some views for making you to understand clearly about the views.

  • Button(UIButton) - It's just a button and it can handle some operations when the button is tapped.
  • ImageView(UIImageView) - This view is used to display images on the screen and it supports most standard formats like jpg and png files.
  • Alert Controller(UIAlertController) - It is used to display alert messages to users and you can create actions with alert controller to perform some operations.
    All views(UIButton, UIImageView, UIAlertController) are subclass of UIView. UIKit contains a huge api's to construct our apps user interface and to respond all system events, interacting with views. It also allows you to access the device features. Please click this link to know more about UIKit.

What is View Controller ?


    View Controller(UIViewController) class is used to manage a set of views and it performs some operations. For instance, when we press the login button in facebook iOS app it'll take you to another screen.

Creating a Project


  • Open Xcode and Create a new project from the file menu.
  • Select Single View Application template and click Next.
  • Give name to product, organization and organization identifier. See below image for reference.


Adding View Controller and Segue


  • Click the Main.Storyboard file.
  • Drag and drop the ViewController from the Object Library into the Storyboard

  • Create a new swift file for second view controller by way of clicking the File -> New -> Cocoa Touch Class and hit next. Note: This file is not created automatically by Xcode like first view controller. For more than one view controller, you've to create manually.
  • Give the class name for second view controller and ensure that it is a subclass of UIViewController and hit next button. Then you'll get another window, just click the create button.
  • Then click the View Controller and then in the right pane, click the identity inspector. In the Custom Class section, choose the SecondViewController from the drop down menu. 


  • Then drag and drop the label, buttons to both view controller.

  • Then we've to add segues between two controllers. Just click Go to Second View Controller button. Then ctrl and drag it into second view controller and release the ctrl button. Then it'll show some options to select, just select show under the Action Segue. It's successfully segued to the Second View Controller. Just do the same procedure for second view controller also. 




  • Just click Go to First View Controller button. Then click ctrl and drag it into first view controller and release the ctrl button. Then it'll show some options to select, just select show under the Action Segue. It's successfully segued to the First View Controller. 


  • Now when the button is clicked it'll take you to the next screen ie Second View Controller and vice versa. 
  • Now your storyboard will look like below image.

Run the App


      Now build the project and run it. Then the app will open in Simulator.




Now when you click the Go to Second View Controller then it'll you take you to the next screen ie Second View Controller and in that screen if you click the Go to First View Controller it'll take you to the previous screen ie First View Controller. That's all!

Download this project

I hope you understand about views, view controllers etc in this tutorial. If this post found useful then please don't forget to share this tutorial. Feel free to ask any questions in this tutorial. See you in the next tutorial...

Happy Coding!! 












Sunday, May 14, 2017

iOS UIAlertController Tutorial

Today we're gonna create an app which will show you an alert dialog when the button is pressed using UIAlertController. Let's get started!


What is UIAlertController ?


          UIAlertController class is used to display an alert message to the user. It also have some default actions and styles. 

Creating a Project


  • Open Xcode and Create a new project from the file menu.
  • Select Single View Application template and click Next.
  • Give name to product, organization and organization identifier. See below image for reference.


Adding buttons and making connections


  • Now click the Main.Storyboard file.
  • Drag and drop the Button from the Object Library into the View
  • Now click ctrl and drag from the button to ViewController
  • Then change the connection from Outlet to Action


  • Then name it and click connect.

ViewController Code



 @IBAction func showAlertDialog(_ sender: Any) {
        
        //Creating alert and enter any string for title and alert messages
        let alert = UIAlertController(title: "Showing alerts", message: "Hey iOS Developers", preferredStyle: UIAlertControllerStyle.alert)
        
        //Creating actions
        let action = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)
        
        //Adding actions to alert
        alert.addAction(action)
        
        //After configuring the alert controller with actions. Then present it to ViewController
        present(alert, animated: true, completion: nil)
        
    }
    


Run the App


      Now build the project and run it. Then the app will open in Simulator


Now when you click the Show Alert button then it'll show you the alert dialog box.






Finally, we finished and executed the Alert Dialog using UIAlertController class. I hope you understand this tutorial. Share this tutorial if you liked it and feel free to comment if you've any doubts in this tutorial.

Happy Coding :)

Sunday, April 30, 2017

Saturday, January 7, 2017

Swift Tutorial - Part 1

Hi developers, Today we're gonna learn what is data type, variable, constants, optionals and more in Swift Programming language. Let's get started!




Variables:


      Variables are used to store some values, when you creating a new variable the system will allocate some memories in memory(RAM). In that memory, you can store any values with any data type.

Data Types:


      Data Types are normally used to store values in variables with some type such as Int, Float, Double, Boolean, Character etc.

             Integer - This data type is used for storing a whole numbers which means you can store only the numbers without decimal points. Integers have two types they are signed and unsigned integer. Signed Integers are represented by Int8, Int16, Int32 and Int64. Unsigned Integers are represented by UInt8, UInt16, UInt32 and UInt64.

 
    var myInt = 4

    //or you can use the Int as datatype to create variables
   
    var myIntTwo: Int = 5 

             Float - This data type is used to store floating point numbers. It's smaller in size when compared to Double and it holds 32 bit floating point number with 6 decimal places.

 
    var myFloat = 4.1459

    //or you can use the Float as datatype to create variables
   
    var myFloatTwo: Float = 4.1459 

             Double - This data type is also used to store floating point numbers. It's bigger in size when compared to Float and it holds 64 bit floating point number with 15 decimal places.

 
    var myDouble = 4.1459

    //or you can use the Double as datatype to create variables
   
    var myDoubleTwo: Double = 4.1459 

             Boolean - This data type is used to store true or false value. It is used for conditions.

 

let isFirstTime = false
      
let noInternetConnection = ture



             String - It is used to store collections of characters within the double quotes.

 
    
       var myString = "Hello iOS Developers"

       //or you can use the String as datatype to create variables

       var myStringTwo: String = "Hello iOS Developers"
 


             Character - It is used to store a single character such as alphabetic letter, symbols etc. Swift stores the character internally as a grapheme cluster(made up of two or more unicode point).


  
    
       var myCharacter = "R"

       //or you can use the Character as datatype to create variables

       var myCharacterTwo: Character = "V"
 


Type Aliases:

 

         In swift, you can create your own name for default data types such as Int, Float, Double etc.

 
    
     typealias APILevel = Int
  
     var android: APILevel = 4

     print(android)
 


Type Inference:

 

         Swift compiler automatically detects which compiler you're using for your variable. So you no need to specify type for the variables.

 
    
     var varOne = 4  //It is inferred to type Int
     print(varOne)

     var varTwo = 2.3453    //It is inferred to type Float
     print(varTwo)
 

Type Annotation:


         You can provide the data type while creating the variables to represent what kind of values the variable can store.

 
    
     var varOne: Int = 4  //It is type annotation
     print(varOne)

     var varTwo: Float = 2.3453    //It is not a type annotation
     print(varTwo)
 

Semicolons:


          In swift, you no need to use semicolons for each statement but if you're writing the statement next to one another then you've to use semicolons to separate the statements.

 
    
     var varOne: Int = 4; print(varOne)


Printing Variable:


          In swift, you can print the strings using print() method and also you can interpolate a variable value by adding the variable inside the open and close parenthesis and escape it with a backslash.


  
    
       var iosVersion = 9

       print("You're using iOS Version \(androidVersion) in your iPhone") 
 


Optional:

 

       Optionals in swift can hold either a value or no value. According to Apple's documentation. Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. 


 
    
  import Cocoa

  var myStringVar: String? = nil

  if myStringVar != nil { 

    println(myStringVar) 

    }else {
 
     println("It has nil value") 

  }

 



Output: 

    myString has nil value

      Automatic Unwrapping:


               By using exlamation mark instead of question mark, you no need to unwrap the optionals manually. It is automatically unwrap the optionals for you and you can get the assigned values correctly.


 
    
 
   import Cocoa

   var myStringVar: String!

   myStringVar = "Hello, Swift developers"

  if myStringVar != nil { 

     println(myStringVar)

  }else { 

    println("It has nil value")  

 } 
Output: 
 Hello, Swift developers

      Forced Unwrapping:


               If you declared a variable as Optionals using question mark. To get the value of that variable(optionals) you've to unwrap it. To unwrap, you need to put exlamation mark at the end of the variable

 
    
 
  import Cocoa

  var myStringVar: String?

  myStringVar = "Hello, Swift developers"

  if myStringVar != nil {

     println( myStringVar! )  //Unwrapping the variable

}else {

     println("It has nil value")

} 
Output: 
     
 Hello, Swift developers
If you didn't unwrap it then your output will look like below

  Optional("Hello, Swift developers")
 

Constants:

 

       Constants are used for creating a variable with fixed values. The values of the constant variable doesn't change while execution. Once you defined your values then you can't change it anywhere. Constants can be used with data types like String, Int, Float and Double etc.

To make the variable as constants you've to use let instead of var


 
    
    import cocoa

    let myconstant = 5
    print(myconstant)


Name your constants with letters, digits and underscore symbol. It must begins with letter or underscore character.

Download Playground files : 

    

Friday, January 6, 2017

iOS Development Tutorial - Cat Years App

In this tutorial, we're gonna learn how to create a Cat Years app. We're going to find the Cat's age in this app. Our app allows you to enter any number and it's multiplied by seven. Then it is shown above the cat image. Let's get started!




Steps:

  1.  Open the Xcode from the launchpad.
  2.  Go to file -> New -> Project.
  3.  Then you've to click Single View Application template.
  4.  Enter your product name(app name), organization name, identifier.
  5.  Select Swift as your language.
  6.  Finally, set iPhone as your device.

Now in left pane, just open the project navigator and click the Main.Storyboard file. It'll open the device in the interface builder.

It's time to drag and drop your views(Label, TextField, Button, ImageView) from Object Library(it's in right pane) into View Controller(Layout). See the image below and do it like that. I hope it's easy for you...




Then click the TextField view and add "enter any number" as placeholder from the Attribute Inspector(It's in right pane) & also set keyboard type as Number Pad.

Now open the ViewController.swift file. Then start writing your code like below.
 

    import UIKit

    class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!
    @IBOutlet var ageResults: UILabel!
    
    
    @IBAction func submitButton(_ sender: Any) {
        

       // print(textField.text!)
        
      var myVal = Int(textField.text!)! * 7
        
        ageResults.text = String(myVal)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 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.
    }


}

By default, ViewController.swift file comes with viewDidLoad and didReceiveMemoryWarning methods.

viewDidLoad() - This method is called, when the app starts and shows the layout to you. You can check this out by way of printing( write this print("viewDidLoad method called") method inside the viewDidLoad method ) something in the console.

didReceiveMemoryWarning() - This method is called when the device receives memory warning, it means the app force stopped due to low memory on your device.

We're just creating a variable called myVal. Then store the integer value which is taken from TextField & multiplied by seven and type cast it into Integer.

Simply assign the myVal values to ageResults variable by type cast the myVal into String data type. That's all.

Now, To run the application click the Run button(it's in left top corner or just click the CMD + R to run your project).  Okay our app is ready to start and I know you're eager to find our cat's age :)

Output:





Download the project from GitHub

Happy Coding! See you in the next tutorial..

Saturday, December 31, 2016

Start developing iOS apps with Swift

           Swift is a new programming language developed by Apple Inc. The swift was released in 2010 by Chris Lattner. Swift uses the modern programming language structures and it is same as objective c like syntax. You can create iOS, OS X applications with Swift programming language. Swift comes with Playground to write their swift program and the output is displayed in right side. It shows the results very fast and you no need to click any run buttons to execute the program. It is very interesting know ? Swift has a lot of features and it has a huge libraries too. The extension of swift program is .swift.

Swift Playground is only for learning purposes and to write swift program you need to install Xcode on your Mac OS. To install Xcode, you wanna create an account at Apple Developer site and then download the Xcode or else you can download it from Mac AppStore itself. Just search for "Xcode" in the search bar on top right corner of AppStore. Once you installed, then open it and select Get started with a playground and give name to the playground. Then select iOS as platform now you'll get the playground and then you can start write your swift code.




Let's get started with simple swift code.


For iOS, You've to import UIKit
    
    import UIKit
    var stringVal = "Hello World"
 

For OS X, You've to import Cocoa 

      
    import Cocoa
    var stringVal = "Hello World"


 
In both program, you'll get the Hello World as output in right side of the playground. It's pretty awesome know ? You're getting your results without clicking any run button. Playground is really a good one to learn swift. Finally you've created your first swift program :)

Imports statement

     In swift, you've to use import keyword to import any Objective C framework in the swift program.

Tokens

     Token is same as in other programming languages like C,C++ and Java etc. Token is a keyword, identifier, constants, symbols etc. You can see many tokens in a small piece of swift code.
For ex : print,import.

Identifiers

     Identifier is the name used for naming the variables, functions etc. Identifier starts with an alphabets from A to Z(uppercase) or a to z(lowercase) or starts with underscore symbol with some characters and numbers.

Comments

      Comments are mainly useful for developers to understand the code. It is ignored by the compiler while executing the code. Two types of comments used in the swift programming language. 
For ex : In app development, the developers will write comments above the code to understand the logic. 

Types : 

       1. Single Line Comment  
       2. Multi Line Comment 

 

 Single Line Comment:
      It starts with // and followed by some characters 

       // This is swift programming language
 

Multi Line Comment:
       It starts with /* and followed by some characters and then it ends with */

   /* This is swift programming language
     Hello Swift developers */

Keywords

      Keywords are predefined words in swift. So you don't use these words to create variables, constants and functions etc.  

Ex : class, public, private, var, do, nil, self, if, break, func, init, internal and so on.

Swift is the alternative programming language for objective c and swift is the future programming language to write iOS and OS X apps. I hope now you'll came to know about swift. In next tutorial, we'll see about the usage of variables, constants etc

Happy Coding...

Sunday, December 25, 2016

iOS Development Tutorial - Hello World

Before getting started with iOS programming you've to install some softwares for creating iOS applications. I posted a tutorial for downloading and installing the Xcode. Kindly click this link if you don't have Xcode on your machine.

Okay guys now let's start to create our first Hello World program in iOS :)



Steps:


   1. Just open the Xcode from the launchpad.

   2. Then you'll get a Xcode's welcome screen.

   3. Click the Create a new Xcode project.

   4. Drag and drop the label from the Object library into Storyboard.

   5. Position the label into center and rename with any name.(in our case, it's hello world)

   6. Then run your app.


Below image is the startup or welcome screen of Xcode. Just click the 2nd option to create a new Xcode project.




After clicking the Create a new Xcode project. You'll see a window with a collections of templates to create iOS apps. Select the Single View application.






and click Next. Now you've to provide some project info such as product name, team, organisation name, organisation identifier, Bundle identifier etc.






Product Name: This is the name of your project(app name).

Team: Sign in with your apple id and assign your account as Team.

Organization Name: Enter your organization name here.

Organization Identifier: Enter you're website url in reverse order.

Bundle Identifier: It automatically entered and it's not clickable. Just leave it.

Language: Select the language to write iOS Apps. The languages are Swift and Objective-C.

Devices: Select any device between these Universal, iPhone, iPad to create your application. The app runs only in the selected device. Universal is common to both the iPhone and iPad. So it can run on both devices, iPhone is only specific to iPhone device, it'll run in iPhone and iPad is specific to iPad devices and it runs in the iPad.



Then after entering all the project details, click Next to enter into coding environment.






Now you'll see the nice Xcode interface. Xcode has three pane(left, center, right)


Left Pane - It shows the collections of project files.

Center Pane - It is the center pane of the Xcode, here you'll see the Storyboards, ViewController, Configuration settings and more.

Right Pane - It shows the inspectors such as File inspector, Quick help inspector, Identity inspector, Attribute inspectors, Size inspectors, Connections inspector and also a File Template library, Code snippet library, Object library, Media library.

In the center pane, you can see there's a lot of settings like app name, version, signing certificate, deployment target, app icons and more for the project. It can be changed at any time so we don't want to focus in this part. Let's move on to next step...



Now click the Main.storyboard file in the from the project navigator which is in the left pane of Xcode. See the below image





Now just drag and drop the label into View from the Object library which is in the right pane of Xcode and place it into center of the layout(when dragging inside the layout you can see the vertical and horizontal line to position accurately). Then click the label and change the text of the label. You can also change the properties of the label such as text, color, fonts, alignment, background color, line break, shadow etc. Just play around with all properties.



Now build the project and run it by clicking the run button. Then it automatically starts the simulator. You can change any simulator(In my case, it's iPhone SE)





Oooooo boom!!!! Finally we just created our first iOS Application. It's awesome right ?


Simulator allows you to test your app like in iPhone. It has many features and it act as real device. But for some cases, you want to use the original iPhone(not the simulator).

 It has some button functionality as well. For simulator buttons, click the Hardware menu in the menu bar of the simulator. Then you'll see a lot of options for using the simulator like iPhone.

I hope you enjoyed the tutorial and now you came to know how to create iOS Applications. See you in the next tutorial.

Happy Coding...!