Pages

GitHub Twitter LinkedIn Facebook Pinterest Google Plus
Coder Earth

// Learn to code...

  • Home
  • iOS Development
    • Xcode Installation
  • Android Development
    • Android Studio Installation
    • RecyclerView
  • Python Programming
  • Java Tutorials
    • Java OOPS
      • Encapsulation
      • Abstraction
  • Downloads
    • Xcode
    • Android Studio
    • Android SDK
  • About
Whenever you create multiple view controllers, you'll need to pass data from one view controller to another view controller in any situation. There are many ways to pass data from one view controller to another. Today we're going to learn simple method to pass data using Properties. Let's get started.

Properties are the variables, every instance of the class have property so that you can easily pass the data just by creating the instance of destination view controller and assigning the values to the properties of destination view controller.


Steps : 

  • Create new Xcode project. Then change the default ViewController name into FirstViewController(CMD + click via tracpad - > Rename)
  • Drag and drop another view controller from Object Library into Interface Builder
  • Then create a new View Controller Swift file for SecondViewController
  • Drag and drop label, textfield and button into FirstViewController. Also drag another label for SecondViewController to display the data from FirstViewController

FirstViewController :

import UIKit

class FirstViewController: UIViewController {
    
    var data: String? = ""
    @IBOutlet weak var dataField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        if dataField.text != "" {
            data = dataField.text!
        } else {
            print("Please enter any data in textField to pass the data from current vc to next vc")
        }
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SecondVC") as! SecondViewController
        vc.textVal = data!  //Assigning data for second view controller
        present(vc, animated: true, completion: nil)
    }
}



SecondViewController :

import UIKit

class SecondViewController: UIViewController {

    var textVal: String = ""
    @IBOutlet weak var txtLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        txtLabel.text = textVal
    }
    @IBAction func goToFirstVC(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

See you in the next tutorial...

0
Share
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 💻








0
Share
       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 :)

0
Share
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!! 












0
Share
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.




Download this project


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 :)

0
Share

0
Share


0
Share
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 : 

     Variables and Datatypes 
    

0
Share
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..

0
Share
Older Posts Home

Stack Overflow

profile for Vinoth Vino at Stack Overflow, Q&A for professional and enthusiast programmers

About Me

Vinoth Vino

iOS Developer | SOReadyToHelp | Swift | Open Source Contributor

Facebook Page

Popular Posts

  • Contacts Framework in iOS
    Apple provides ContactsUI framework for displaying and selecting the contacts. It fetches all the contacts from the iPhone's Contact A...
  • 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...
  • Passing Data Between View Controllers Using Properties In iOS
    Whenever you create multiple view controllers, you'll need to pass data from one view controller to another view controller in any situ...
  • Encapsulation in Java
    In last tutorial, we saw how RecyclerView is implemented in Android. Now, I'm gonna to explain what is encapsulation and what's the...
  • Getting started with Python
    What is Python ?      Python is a object oriented and high level programming language which is created by Guido Van Rossum. Python has c...

Categories

abstract class abstract methods abstraction alert android androidstudio apple arraylist button contacts data hiding Datas datatype dialog encapsulation generics imageview ios ipad iphone java label list item multiple view controller programming python recyclerview sdk segue simulator Store storyboard swift uialertcontroller User Defaults variables xcode

Popular Posts

  • Contacts Framework in iOS
    Apple provides ContactsUI framework for displaying and selecting the contacts. It fetches all the contacts from the iPhone's Contact A...
  • 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...
  • Passing Data Between View Controllers Using Properties In iOS
    Whenever you create multiple view controllers, you'll need to pass data from one view controller to another view controller in any situ...
  • Encapsulation in Java
    In last tutorial, we saw how RecyclerView is implemented in Android. Now, I'm gonna to explain what is encapsulation and what's the...

Labels

Datas Store User Defaults abstract class abstract methods abstraction alert android androidstudio apple arraylist button contacts data hiding datatype dialog encapsulation generics imageview ios ipad iphone java label list item multiple view controller programming python recyclerview sdk segue simulator storyboard swift uialertcontroller variables xcode
Copyright © 2015 Coder Earth

Created By CoderEarth