Advertise

Sunday, March 5, 2017

iOS: Picker View and Date Picker View integration with TextField in Swift 3.0



While you are creating a form like user profile you need to add some fields and among that you need to give user a action to choose between them. For Gender, Country, State, Date fields Picker View is a best option to fulfil our requirement. Picker View comes in picture because if you have set date field and user enters his name then? How you evaluate user enters proper date ? Same way if you set country name and user enters state name then? How you identify the country name is correct or not? In global application it will store in central database and reflect in every platform, so it reflects wrong information everywhere. To prevent this issue, you can give user a bunch of options from where he/she can choose.

Due to, screen size limitation, you can add picker view as a fade in when required and fade out after selection. In this tutorial, we will integrate Picker View and Date Picker View similarly as shown above image.

So, Let's start coding instead of doing stories:

First, Create a project named "PickerView Demo" or whatever you like and create a view as shown below. You just need to add two labels and two TextFields.




Give textfield outlet to it's Controller swift file:

 @IBOutlet weak var countryNameField : UITextField!
 @IBOutlet weak var dateField: UITextField!


We are going to PickerView to select country name and choose Date PickerView to select Date. For, Country name, first we should have array with Country name list. So, Add below code just below above code.

let countryArray = ["India","United States", "United Kingdom","Canada","Australia","UAE","Russia","China"]

Then, add two controller PickerView and DatePicker:

@IBOutlet var countryPicker : UIPickerView!
@IBOutlet var datePicker : UIDatePicker!

In both picker view, we need to initialise component and give them a array which is used to display and also connect it with text fields. This will done with simple 3-4 line code. It is not a rocket science. Just copy and paste below code into viewDidLoad() method.

        // Country PickerView
        countryPicker = UIPickerView()
        countryPicker.tag = 1
        countryPicker.delegate = self
        countryPicker.dataSource = self
        countryNameField.inputView = countryPicker
        countryNameField.text = countryArray[0]
        
        //Date Picker
        datePicker = UIDatePicker()
        datePicker.tag = 100
        datePicker.datePickerMode = UIDatePickerMode.date
        datePicker.addTarget(self, action: #selector(self.setDate(_sender:)), for: .valueChanged)
        datePicker.timeZone = TimeZone.current
        dateField.inputView = datePicker

Above code easily understandable by you and no need to describe... I guess. Now, move on to further step. as, above code we are defined setDate(_sender:) method in DatePicker. So, we need to define it and add code for display user selected date into dateField.

func setDate(_sender : UIDatePicker){
        let dateFormatter: DateFormatter = DateFormatter()
        // Set date format
        dateFormatter.dateFormat = "MM/dd/yyyy"
        // Apply date format
        let selectedDate: String = dateFormatter.string(from: _sender.date)
        print("Selected value \(selectedDate)")
        if(_sender.tag == 100){
            dateField.text = "\(selectedDate)"
        }
        self.view.endEditing(true)
    }

Before, going to next step we need to add delegate methods for UIPickerView: UIPickerViewDelegate and UIPickerViewDataSource. Change your Class name code as below:

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource

Now, Final step is to integrate these delegate methods as below:

    //MARK:- PickerView Delegate
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
            return countryArray[row]
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return countryArray.count
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        if(pickerView.tag == 1){
            countryNameField.text = countryArray[row]
            self.view.endEditing(true)
        }
    }

It is very simple code and understandable by anyone. We just define array into pickerView and when user select and row it will print those value into textField. self.view.endEditing(true) is used for disable PickerView.

Download Full Source Code






Friday, March 3, 2017

iOS : TableView Controller in Swift 3.0


Table View is a vey common and important component to develop application. Usually application contains table view to display bulk of data in single screen.  You can customise table view and make it attractive and eye catching whatever you want to do. It is as simple as other development platforms. However, here I am giving you How to integrate simple table view in iOS application in Swift 3.0.

As you can see in the picture above, We are going to print one list of my friends. Moreover, we will add feature to delete some name from the item list. I assume you know how to create xCode project and familiar with Swift language, Storyboard and xCode 8.

Now let's start from scratch. Create a project named TableViewDemo in xCode and remove initials default file ViewController as we are not going to use it. Additionally, Go to Storyboard and delete ViewController as well. 

Now,
Select your project and press Command+N OR go to File > New > File. Select Cocoa Touch Class and hit Next button.
Add Class name as per your choice but it should be meaningful so we can identify it. To give a better and meaningful name is also important for code development as we need to identify file from bunch of file in big project. Here, I am using "FriendsListController", Choose subclass of : UITableViewController. Don't change anything except this two name. then hit next and press create button.
Here you have created swift file for Table view successfully.  This swift file behaves like backend code part. But You also need to bridge with UI part which you are going to build in Storyboard file. Open Storyboard and Go to Object Library from Right - Bottom part as described in below image and drag-drop TableView Controller into our Storyboard file.




You can also add Navigation bar to your controller for navigating between one screen to another. For that, Go To Editor > Embed In > Navigation Controller. Rest of the work xCode do by itself but make sure you have selected correct ViewController in which you want to add.

Now, We need to tell xCode that this TableView controller is associated with "FriendsListController" file which we have built earlier. For that Go to Storyboard and select TableView Controller > Identity inspector. Add Class name in class field as described below.




Now the file is bridged with UI Controller. One more thing you need to do before leave Storyboard is to give Cell name. For that select Cell which is added by default in table view. Select it and go to Attributes inspector. Add value of Identifier to "Cell". We will use this identification in swift file later.

So, your storyboard looks like below screen.



Now Backend part begins. open FriendsListController File and follow below steps. One of the main component which uses for TableView is Array. It is best way to store list of data into array and integrate it into Table View. It is very simple and efficient way. We will do the same and have created my friend list array and declare it in our file globally. Here is my sample data:

var friendsName = ["Parth Pandya","Aangan Bhatt", "Krishna Pandya","Anuj Patel","Maulik Soni","Vidit Maniyar","Hardik Bhatt"]

We have used var instead of let just because we are going to remove some list item as well in future. I assume you are aware of basic fundamental of let and var datatypes.

You have noticed that some of override methods has been added by default in our class and made it commented. Just uncomment these methods as per our requirement or you can create it again. We will understand each and every methods step by step.

1. numberOfSections : Copy below code into your file

override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

We can set multiple section and bifurcate as per our data but we are using same type of data in single list item so we set it 1. 

2. cellForRowAt indexPath:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = friendsName[indexPath.row]
        return cell
    }

This method defines cell by it's identifier which we have added in storyboard. and then based on that cell we can access cell components like, label, button etc. Label is added by default in tableView cell. IndexPath defines index level of tableView, based on index path we can retrieve data from Array and set it into label. It is as simple as given above.

3. didSelectRowAt indexPath:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You clicked \(indexPath.row) row: Friend Name:\(friendsName[indexPath.row])")
    }

Action required when user clicks on specific item. This method fulfil it and we can add action here. Currently I am printing selected item name in console.

Here, is a code for tableView is completed, if you want to swipe delete action then copy below code in the file.

 override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            friendsName.remove(at: indexPath.row)
            tableView.reloadData()
        }
    }

Above code is override methods to call swipe delete button and perform action when user clicks on Delete button. In this code, we just remove clicked data from array and reload table again.

That's it... Now run the project... It will give you same result as mentioned in first demo image.


Transfer data from one screen to another


For the same example, usually you need to transfer user selected data to another screen. You can do this with more few line of code. Here, When user selects name from friend list, it will redirect to next screen and print selected friend name on screen. I assume you know how to connect two screen with segue in storyboard. Before start understand the steps below:

1. Create another file where you want to transfer data
2. Add segue to connect two controller and name that identifier segue.
3. perform segue in controller from where you want to redirect with data.
4. Set redirected data into the screen. Thats it.

First, Create new cocoa touch swift file named "DetailedViewController" and same as above create new View Controller in Storyboard as well. Same as above, name those view controller and connect it with the swift file. Add one label and connect outlet to our swift file. It will define label into DetailedViewController.

Second, We need to connect FriendsListController and DetailedViewController via segue in storyboard. For that, open storyboard and select Friend List Controller. For that you need to click on Yellow button over the controller as described below.


Click this yellow button + Control Key to create segue between two screen. Drag and Drop it to DetailViewController screen. It will create segue between two. Now, you can see DetailedViewController also get Navigation by default. Name this segue "detailedSegue". We will use this identifier later to access this navigation segue. Your storyboard will look like :



Here, Storyboard task ended, now we need to add some code in both files. For that open "DetailedViewController" swift file and add below code into it.

class DetailedViewController: UIViewController {

    var selectedFriendName : String!
    
    @IBOutlet weak var friendNameLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        friendNameLabel.text = "Selected Friend is \(selectedFriendName!)"
    }
}

Now Open FriendsListController file and add below code:

1. Create one String variable to store selected data:

var selected : String!

2. Modify didSelectRowAt: methods as below:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You clicked \(indexPath.row) row: Friend Name:\(friendsName[indexPath.row])")
        selected = friendsName[indexPath.row]
        self.performSegue(withIdentifier: "detailedSegue", sender: self)
    }

3. Add prepare segue navigation method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "detailedSegue"){
            let destinationController = segue.destination as! DetailedViewController
            destinationController.selectedFriendName = selected
        }
    }

First, we have store selected data in separate variable and call segue in didSelectRowAt: method. prepare segue method is override,  we check segue identifier which we have added in storyboard. If it matches the we have pass selected name to DetailedViewController variable.  Thats It. Now run the project. 

I hope, this tutorial will clear your confusion regarding table view and make it useful. You can download full source code from here.











Friday, March 18, 2016

QR Code Scanner - Generator iPhone / iPad Application



Description:

Change your smartphone into a powerful QR code Scanner utility. Create, use, and save data in a matter of QR Code.
This intuitive, full-featured QR Code utility will change the way you interact with QR Codes and their smart actions and activities.

FEATURES:
----------
1. Scan QR Code quickly.
2. Generate and Save QR Code.

Types Of QR:
----------
1. Free Text
2. URL
3. Contact
4. Phone Number
5. SMS

Save generated QR code in Photos(Gallery).

NOTE: This application will access your gallery(For saving QR) and camera (For scan QR).

Screenshots:



 

 




Sunday, February 7, 2016

Find My Family - Security - iPhone/iPad Application


Description:

Are you worried about family members? Where they are going and what they are doing? Here is the solution and get free from this tension. This application will track your family members and gives you a latest location of your family members ! Good to here, isn't it?

It is very simple to use. You need to create your own account and and use this application. Here is the guide / step by step how to use this app.

HOW TO USE THIS APP?

To easy understanding consider you as a FATHER and you want to track your daughter’s current location.

1. Download and create your own account. (Required information: Name, Email ID, Password, Profile Picture). After create account log-in with your credential.

2. Request your daughter with entering her Email ID. (Your daughter must have this app and need to log-in with her credentials).

3. If your daughter accept your request then and then you will get her location and more details. That's it. (Like Social apps)

NOTE that, If your daughter accept your request, you can track her BUT if she wants to track you she needs to send request and get your permission first.

———
It is very secure application and it will not send your data without your permission. Any user wants to track you he/she needs to send a request you first.
———

DISCLAIMER: 
1. Continued use of GPS running in the background can dramatically decrease battery life.
2. This app will access your gallery to upload profile picture.


IMPORTANT:
———
1. This app will not send any personal data without your permission.
2. This app will access your current location and gallery to upload profile picture.
3. It never Encrypt / Decrypt personal data.
4. All tracking data is stored on secure server, There is no chance to have data.





Screenshots: