Sunday, 23 April 2017

UIPickerView example Swift3 - IOS Tutorial




UIDatePicker-Swift-Tutorial

UIPickerView Introduction

UIPickerView is common control used to allow user select from a list of drop-down option in IOS apps. In this tutorial we will learn how to create UIPickerView in Swift3/Swift language. 
                   This UIPickerView tutorial  is written in Swift language so you need xcode 6 and higher version to run the sample code.

Steps to create UIPickerView in Swift

Step 1: Create a single view application and name it UIPickerView-Swift. Chose development language as swift.

Create-Single-view-application-UIPickerView-Tutorial-Swift-ios


Step 2: Open Main.storyboard and select iPhone SE as our default layout screen so that it can adjust UIPickerView control can adapt to higher device automatically as we are going to use Auto-layouts. Drag UIPickerView on to the view and add constraints to it as shown in the image.

Adding-constraints-to-UIPickerView-Tutorial-Swift-ios

Step 3: Open ViewController.swift and create IBOutlet for UIPickerView added to our view in Main.storyboard. 

    
 @IBOutlet weak var customPicker: UIPickerView!


Step 4: Connect IBOutlet created in last step to UIPickerView in Main.storyboard

Connecting-IBOutlet-to-UIPickerView-Tutorial-Swift-ios

Step 5: In ViewController.swift, set UIPickerView delegates and datasource as shown in below code


 customPicker.delegate=self
 customPicker.dataSource = self


Step 6: Data-source and delegates methods are required to show data in UIPickerView and to know which row is selected by user. For this we create pickerDataSource array that contain list of countries.




 var pickerDataSource = ["India", "Australia", "United   Kingdom", "South Africa"];


Step 7: Since we are with are datasource array it's time to implement our UIPickerView delegates and datasource methods. Below is the code that does the same i.e implementation of UIPickerViewDelegate and UIPickerViewDataSource methods




  func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerDataSource.count;
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return pickerDataSource[row] as String
    }


Step 8: Run your code and you will see UIPickerView showing list of countries we added to our pickerDataSource array.


Step 9: To check which UIPickerView row is selected by user we have to implement one more UIPickerViewDelegate method. Below is the code for the method that shows which row is selected by user

   
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        print(pickerDataSource[row])
    }


Step 10:  Run your app now and when ever you spin the UIPickerView, the above delegate gets called each time as UIPickerView wheel stops thus giving us the user selection. You can check the console of your project.

Where to go from here

In this post you learned about How to create UIPickerView in iOS app using swift/swift3 language. You van download the sample code from here. If you have any questions then feel free to comment.
Happy Coding :)

Sunday, 16 April 2017

How to create UICollectionView in Swift3 - Tutorial


UICollectionView-Tutorial-Swift-3

Introduction to UICollectionView and Swift3 

UICollectionView is control used to create grid based layouts in iOS app development. With the introduction of swift3, lot of syntax changes happened, so let us dive in to the UICollectionView tutorial created in Swift3. We will use custom UICollectionViewCell class in our tutorial.

Steps to create UICollectionView in Swift 3

Create single view application, at this moment you have 3 files. Open ViewController.swift file and create an IBOutlet for our UICollectionView (We will drag and drop UICollectionView to view in storyboard in next step )




Open Main.storyboard and drag UICollectionView to the View Conroller Scene. Connect our IBOutlet, created in last step with UICollectionView.

Create a new UICollectionViewCell class and named it DummyCell (Check-mark "Also create xib file"). Open DummyCell.xib and give it height and width as shown in the image below.

How to create UICollectionView in Swift3 - Tutorial
Create UICollectionViewCell with xib

How to create UICollectionView in Swift3 - Tutorial
Set height and with for UICollectionViewCell


Drag UILabel to DummyCell.xib  and open DummyCell.swift. Create IBOutlet for UILabel, we dragged on DummyCell.xib file.



Open DummyCell.xib and connect IBOutlet with UILabel.

Open ViewController.swift, and create UICollectionViewFlowLayout. Flowlayout is used to tell
UICollectionView following things

  • Scroll Direction
  • Item Spacing
  • line Spacing
  • Size for the cell or item
As we have UIFlowLayout created for our UICollectionView, it's time to register nib for our UICollectionView. This tells the compiler that which xib is going to be used to create cell for UICollectionView. We will also create UICollectionViewDataSource methods/functions to populate our UICollectionView.

Complete Code for UICollectionView using Swift3



Run your code and you will see the UICollectionView with two columns.

Source code for UICollectionView in swift3: UICollectionView-Tutorial.zip

Video Tutorial for UICollectionView in swift3

Sunday, 26 March 2017

Expandable and collapsable UITableView in iOS sdk using Swift3


Expandable and collapsable UITableView in iOS sdk using Swift3 - Tutorial

Introduction to Expandable and Collapsable UITableView

In this tutorial, we are going to create UITableView that will expand and collapse on tap of row or on row selection using Swift3 language for iOS app development. In more common words, showing sub-menu/ sub-items of main menu/item. Example is shown in the below given picture


       

Steps to create Expandable and collapsable UITableView

Step 1: Download the files already created with expandable and collapsable functionality. Download those files from Download Expandable and collapsable UITableView Files

Step 2:  Add the above downloaded files to your project, check mark "Copy items if needed". 

Step 3: We will create our datasource in parent child relationship. Because the classes/files downloaded by us in last step based on parent child relation. The datasource will have parent as of type String and child will be of type Array containing String type values/elements. Below is the code that shows how to create data source for the expandable and collapsable UITableView


Step 4: To use it we will create an object of ExpandableTable and give it frame with 20 pixels gap from top.
4.1) After giving frame we will assign datasource created in last step to dataSourceForPlainTable property of ExpandedTable object.
4.2) Assign delegate to self, as we want to get notified whenever a selection is made by us.
4.3) Finally we will add it as subview to our main viewController. Below is the complete code



Step 5: Run your app and you will see the Expandable and collapsable UITableView. Tap on sub menu/ sub-item. That name will get logged on your project console.

Where to go from here

In this tutorial we learned about how to create Expandable and collapsable UITableView in iOS sdk using Swift3. You can download the full source code from here. Stay tuned for more tutorials...

Monday, 13 March 2017

Integrate instagram login in iOS app using Swift3 -Tutorial


Integrate Instagram in ios swift3

Introduction to the post Integrate Instagram login in iOS app in Swift/Swift3

Instagram is the popular app that allows user to share pictures and small videos with their followers and people around the world. In iOS app, developers  can utilize Instagram Api in two ways

1) Login to the app using Instagram credentials
2) Share picture from the app to Instagram

For 2nd option you can check share pictures to Instagram programmatically from iOS app  as in this post we are only going to cover login via Instagram in swift/swift3 language. If you are looking for objective c version then please check integrate instagram in ios objective C

Register your app with Instagram.

Now Instagram requires developer to submit there app for approval as like Facebook. Developers have to build their app in sandbox mode and when they want to go to the stores, they need approval from Instagram so that their could work in live environment.

Follow the steps to register your app with Instagram,

1) Login to https://www.instagram.com/developer/

2)  Click on Register client, by clicking on Register Your Application button (shown in image below)

 3) If you had created apps before this one then you have to click "Register a new client"

4) Fill in all the details under "Details" tab and under "Security" tab uncheck "Disable implicit oAuth" option. This will tell Instagram that we are using unsigned login approach. Signed login approach will be covered in separate tutorial.

UnCheck_Disable_implicit_OAuth

5) Click Register, to confirm your app registration with Instagram.

6) As soon as you register app,  you will be navigated to page where all your apps are listed. Click on manage button so that you can get client-secret for your app.

Code to login with Instagram  in swift/swift3 language

I am not going to cover the app building from scratch, instead we will cover only Instagram-login View controller code.

First create a constant file as shown below


Create an new UIViewController class and name it as InstagramLoginVC.  Open InstagramLoginVC.swift and declare our  UIWebView and  UIActivityIndicatorView IBOutlet's.




Open your storyboard file or .xib file and drag, drop UIWebView and UIActivityIndicatorView to it. Connect IBOutlet's to both of the controls.

Open your InstagramLoginVC.swift class. First we will create a function named unSignedRequest(), which will make request to Instagram server


Now we call the above created unSignedRequest()  function in viewDidLoad()



As you are seeing that we assigned UIWebView delegate to self in our viewDidLoad() function, it's time to implement UIWebViewDelegates



In above code we implemented UIWebView delegates. Apart from shouldStartLoadWith delegate, rest are simply used to hide and show UIActivityIndicatorView.

In  shouldStartLoadWith delegate, we call a function named as checkRequestForCallbackURL() 
which accepts URLRequest as parameter. But still we did not write it's definition. So without wasting any time just write it



In checkRequestForCallbackURL() , we check for the URL returned by Instagram and if the URL has our REDIRECTURI as prefix then it means we have our access token/ Auth token in it and we have to extract it. At this moment we will stop our UIWebView to load new requests and extract extract it.

Complete code for UNSIGNED Instragram login request in swift/swift3 

 

Where to go from here

 In this article you learned how to make UNSIGNED login request to Instagram using Swift3 in iOS app development. Download the source code from here  InstagramLogin-Swift.zip

If you have any questions then please feel free to comment. Thanks for reading. 

Tuesday, 28 February 2017

Login and get profile information from Facebook using Facebook swift3 SDK in iOS


Facebook login and profile information using swift3

Introduction to our tutorial Login and get profile information from Facebook using Facebook swift3 SDK in iOS

                                      With the introduction of Swift3 by Apple, all of sudden every aspect of ios development changes. Today in every apps, login through social networking is used. Facebook also released their SDK with swift3 language and in this tutorial we will learn how to login using Facebook swift3 SDK and get logged in user profile information.

Set up app on Facebook developer and add app ID to your project .plist file

Create a new project (I am considering that you know how to create a project using xcode). Now go to https://developers.facebook.com/

On right side corner, you will find "My Apps", on its expansion click "Add a new app". Enter the information as per the fields. Select the platform for your app  as iOS.
Select platform for your facebook app as iOS

Skip the firs and second step as we are going to use swift SDK and that can only be installed using pods. Enter you bundle id of your project (it should be same as listed in your project, otherwise Facebook login will not work).  Skip 4th step and copy the .plist info shown in 5th step to your project .plist file (if you don't know how to do it then right click on your project .plist file and open it as source file, after that paste the info as shown in the Facebook developer portal).

Install Facebook SDK using pods

You can install Facebook SDk using cocoa pods by visiting this link https://github.com/facebook/facebook-sdk-swift

For how to install cocoa-pods, you can learn more about  here 

Integration of Facebook login with Swift3 

At this stage we are done with our Swift3 SDK for Facebook. Open your AppDelegate.swift and import FacebookLogin and FacebookCore frameworks. Made changes to your AppDelegate.swift file as shown below

<1--code gist="" here -->


Open you ViewController.swift file, create an IBAction for Facebook login and named it loginWithFacebook. Below is the code that get authentication token from Facebook. We are showing code for the whole file, and please import frameworks as done in AppDelegate.swift.

<1-- code gist="" here -->

If all goes well without any error, you will get authentication token from Facebook. 

You can use below code to get user basic information, like name, email and Facebook ID.


<1-- code gist here-->

Where to go from here 

In this tutorial, you learned how to login and get profile information from Facebook using Facebook swift3 SDK in iOS.  You can download the source code from Facebook-login-with-swift3. If you have any questions, feel free to comment and I will try to answer those as soon as I can. Stay tuned for more tutorials on swift 3.


Sunday, 5 February 2017

How to create UIDatePicker in swift - Tutorial




UIDatePicker Swift3 Tutorial

Introduction to UIDatePicker in Swift

UIDatepicker is the control provided by UIKit framework packaged with xcode IDE. It allows user to pick date from the spinning wheel that act same as drop down option in web. You can use UIDatePicker in your app where you want to allow user to enter or input
  • a Date
  • both Date and Time
  • only Time
  • Countdown timer

Steps to create UIDatePicker in swift

Step 1: Create a new xcode project and name it UIDatePicker-Swift, if you are not familiar with creating xcode project you can check here

Step 2: Open Main.storyboard and drag UIDatePicker on to the view.

UIDatePicker-added-to-the-view
UIDatePicker added to the view
Step 3: Add constraint to UIDatePicker. Shown in the image below

Add-constraints-to-UIDatePicker
Add constraints to UIDatePicker

Step 4: Open ViewController.swift and create an IBOutlet to UIDatePicker

  
  @IBOutlet weak var datePicker: UIDatePicker!


Step 5: Open Main.storyboard and connect our IBOutlet created in step 3 to the UIDatePicker placed on the view as shown in the image below

Connecting-IBOutlet-to-UIDatePicker
Connecting IBOutlet to UIDatePicker
Step 6: Set current date as our UIDatePicker date, so that when screen launches/shown to the user it display current date as selected date


  override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.datePicker.date = NSDate.init(timeIntervalSinceNow: 0) as Date
 }

Step 7: Run your code, you will see UIDatePicker showing current date as selected date.

Get selected date from UIDatePicker

Till now you created UIDatePicker successfully, now the question is  how can we get date selected by user. For this we can do two things

  • will add a button and add IBAction to it so that when user tap on button we will get our selected date. 
  • Add our IBAction to UIDatePicker and assign it to ValueChanged event, so that whenever UIDatePicker date changed it notifies us
Step 8: Open Main.storyboard and add UIButton to it. Add constraint to it as shown in below image

Adding constraints to UIButton
Adding constraints to UIButton
Step 9: Open ViewController.swift and create our IBActions, one for 
  • Button Tap event 
  • UIDatePicker value change event
Below is the code that solve our purpose in both ways


   @IBAction func doneWithDateSelection(_ sender :AnyObject) {
        print("Date Selected through button  == ", datePicker.date)
    }
    
    @IBAction func pickerDateSelectionChanged(_ sender :AnyObject) {
        print("Date Selected via UIDatePicker value change == ", datePicker.date)
    }


Step 10:  Open Main.storyboard and add IBaction to UIButton and UIDatePicker as shown below

Connecting IBAction to UIButton
Connecting IBAction to UIButton
Connecting IBAction to UIDatePicker
Connecting IBAction to UIDatePicker
Step 11: Run your app and you will see date in console when you tap on Button or change UIDatePicker value.

Step 12: If you see your date on console, you will get time also. In order to get only you have to get date with dateformatter class given by xcode. Below is the complete code that

Complete code which print date only when user tap on button or change date picker value

Complete Code


 //
//  ViewController.swift
//  UIDatePicker-Swift
//
//  Created by Aman Aggarwal on 12/21/16.
//  Copyright © 2016 iostutorialjunction. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    var dateFormatter = DateFormatter()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.datePicker.date = NSDate.init(timeIntervalSinceNow: 0) as Date
        dateFormatter.dateFormat = "MM/dd/yyyy"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func doneWithDateSelection(_ sender :AnyObject) {
        
        print("Date Selected through button  == ", dateFormatter.string(from: datePicker.date))
    }

    @IBAction func pickerDateSelectionChanged(_ sender :AnyObject) {
        print("Date Selected via UIDatePicker value change== ", dateFormatter.string(from: datePicker.date))
    }
    
}

Where to go from here

In this tutorial you learned about UIDatePicker in swift and how to print/select date form UIDatePicker without time using dateformatter. You can get the whole code sample from here .
If you have any concerns than you can comment here. Happy Coding :)






Sunday, 15 January 2017

programmatically share image to Instagram through iOS app

Post image to Instagram programmatically in iOS app - tutorial

Introduction to the post programmatically share image to Instagram through iOS app

Instagram is another most popular social platform for sharing images. Now days, every app share image to Instagram too. Since like other social platforms Instagram does not provide developers permission to write image directly on the user Instagram wall. So for this we can use UIDocumentInteractionController provided in objective c and swift language in X-code.

For sharing/posting image to Instagram, you should have two things
1.  Instagram should be installed on your device.
2.  User must be logged-in onto Instagram app prior to sharing/Posting image.

NOTE:- If user is not logged in then you have to log him/her in first and then allow him to open your app and re share it.

Code for sharing image to Instagram through iOS app - objective C



Code for sharing image to Instagram through iOS app - Swift 3


  
For sharing image to Instagram, first we created an image with extension .igo(its instagram file extension so that the Instagram app can be shown in UIDocumentController) then save it to our document directory by first removing any image the already written on that location and re writing new image using writeToFile method, that we are going to share to Instagram. Then we will create our UIDocumentController instance and gave it the path of our sharing image that we wrote in document directory. After finish this, we have to specify app identifier to let compiler know which app is capable of opening .igo type document, here we gave "com.instagram.exclusivegram". Lastly, we present our UIDocumentController to user.