Sunday, 15 April 2018

Learn about closures and how to write closures in swift


Learn about closures and how to write closures in swift

What are closures?

As per apple documentation, closures are self contained blocks of  functionality that can be passed around code. In swift these are similar to what we called blocks in objective c and lambda in other languages. The definition is quiet complex to understand, so in simple words we can define closure as a chuck of code that can perform certain functionality or calculations and then pass the control to the class from where its getting called or invoked, like a callback.
                                         Example of closures are completionHandlers we often used while making an API request. So in this tutorial we will learn how to write closures in swift, before we start learning how to write closures, we must knew how to write function (i hope you are aware of syntax to create a function), if you are novice and learning swift then below is the code snippet for the same


Difference between function and closure

1. Closures don't have func keyword
2. Closures don't have name
3. Closures have in keyword (function don't have)

Writing closure

At this point we knows the difference between a function and closure, so let us make our function a closure.

Step 1: Remove 'func' keyword from our function and name 'welcomeGuest' also removed. We satisfied two conditions of closure that it doesn't contain 'func' keyword and name. Our closure will look like


Step 2: Third point tells us that closure has 'in' keyword, so we need to place 'in' keyword in place of opening curly brace of and move that open curly brace to start of the closure. Our code will look like





Step 3: At this point compiler is showing you an error "expected declaration", so in order  to remove  error, we need to assign the closure to a variable, as shown in below code snippet





Step 4: We are done with closures as we successfully write a closure that returning a string value. In order to call our closure inside viewDidLoad function as shown below


Where to go from here:

In this tutorial, we learned how to write closures in swift, We learned about difference between closure and function and how to write closure in swift and use them in our code. If you have question, please feel free to ask.











Monday, 26 March 2018

Set placeholder to UITextView in swift4

Set placeholder to UITextView in swift4

Introduction to tutorial - set placeholder to UITextView: 

Placeholder is a property associated with input UI components that works as a hint to the user in mobile app development. UITextField has placeholder property but not UITextView in swift. So for UITextView placeholder we need to write some code as we don't have pre-existing inbuilt  property provided in the iOS SDK for swift language. In this tutorial we will learn how to set placeholder property to UITextView in swift language. Follow the below steps to learn how to set placeholder to UITextView in swift

Step 1: Create a single view application project and name it "UITextViewPlaceholder". Open "Main.storyboard" and drag UITextView to UIView of viewcontroller. 


Set placeholder to UITextView in swift4

Step 2: Add constraint to UITextView as shown in below figure

Set placeholder to UITextView in swift4


Step 3: Open "ViewController.siwft" and create IBOutlet for UITextView, added in step 1.

 
 
 

 
 


Step 4: Attach IBOutlet to UITextView in "Main.Storyboard".

Step 5: In "ViewController.siwft", inside 'viewDidLoad' function set text that will act as placeholder to UITextVie. We will set its textcolor and font so that it looks like a placeholder. Also we will set UITextView delegate.


Step 6: If you run the app at this point, you will see UITextView displaying placeholder text.

Set placeholder to UITextView in swift4


If you type now, you won't see placeholder stays there and text is getting appended to it. In order to remove placeholder as soon as use starts typing we need to take advantage of UITextView delegates methods.

Step 7: Implement below code, here we are using UITextView delegate methods.


textViewDidBeginEditing: In this delegate method, we detected if our UITextView begins editing and if the text matches to our placeholder text then set it's text to  empty string. Also we change textcolor and font so that user feels that he is writing and its not the placeholder which grows.

shouldChangeTextIn: This delegate method is used so that we can dismiss keyboard. As soon as user hits Done button of keyboard we detected new line as UITextView append new line (\n) when user presses done or return key of keyboard (default implementation by iOS).

textViewDidEndEditing: In this delegate method, we do exactly opposite of what we done in first delegate method (textViewDidBeginEditing). Here, we detected if UITextView text is empty or blank then we set placeholder text, font, textcolor to it.

Run your app now and you will see placeholder for UITextView is working perfectly. Below are the screen shots of the output

Set placeholder to UITextView in swift4

Set placeholder to UITextView in swift4

Where to go from here:

In this tutorial we learned, how to set placeholder to UITextView in swift. Though there are so many libraries out there to handle this stuff of UITextView placeholder, this the most simplest way of setting placeholder to UITextView. You can grab the source code for this tutorial from UITextView Placeholder swift source code





Wednesday, 21 March 2018

Draw route on iOS map (MapKit) using MKDirections in swift4

Draw route on MapKit using MKDirections in swift4

Introduction to draw route on iOS map (MapKit) using MKDirections in swift4

In this tutorial, we are going to learn how to to draw route on MapKit (apple map) between two locations using swift4 language. We will use MKAnnotation's to draw pins for source and destination. For getting route, we will use MKDirection class and then draw polyline (commonly known as route) on the MKMapView. Follow the below given steps to learn how we can draw route between two points on MKMapView in swift4.

Step 1: Create a new single view project, name it "DrawRouteOnMapKit". Open "Main.storyboard" and drag 'Map kit view', aka mapview on to view.

Draw route on MapKit using MKDirections in swift4


Step 2: Open "ViewController.swift", create IBOutlet for the map kit view we added in last step.



Step 3: Open "Main.storyboard", connect IBOutlet to the mapkitview created in step 1.

Step 4: Open "ViewController.swift", now its time to create class for the pins or MKAnnotations that will act as pole for source and destination location. Below is the code for creating custom class for MKAnnotation.


Step 5:  As we successfully created custom class for our pin or annotation. It's time to get directions between two locations and draw route on Mapkit aka mapview. In ViewDidLoad, first we will create coordinates for source location and destination location.


Step 6: Now we will use our custom MKAnnotation class to create pins for source and destination locations with the coordinates set in the last step.


Step 7: If you run the app at this moment, you will see two pins on that map (Please go to USA on the map by zooming or pinching on it if your current location is far from USA, because we set source and destination of two cities of USA).

Draw route on MapKit using MKDirections in swift4


Step 8: In order to get directions for routes between our two locations, we need to create a placmark using MKPlaceMark class which accepts coordinate. We will create two placmarks for source location and destination location.



Step 9: To get directions, we will use MKDirectionRequest class. MkDirectionRequest class has properties like source, destination, transportType (mode of of our transport either automobile, walking, transit, any). Lastly, we will use MKDirection class, and request for directions. We will get directions in the callback. Below is the final code


Run the app, at this point you will see pins but no route. For this we need to implement one delegate method of MapKit so that we can render the route or polyline.


Step 10: Set delegate of mapview(MapKit) to self and then implement the delegate method



Draw route on iOS map (MapKit) using MKDirections in swift4

 

 Where to go from here:

In this tutorial, we learned how to draw route between two location in iOS map (MapKit). You can also download source code from https://goo.gl/tmi4es

Sunday, 4 March 2018

Get user location in swift4 (CoreLocation)

Get user location in swift4 using CLLocationManager

Introduction to the post get user location in swift4 using CLLocationManager 

In this tutorial, we will learn how to get user current location in swift 4. For getting user current location, we will use Corelocation framework for location updates and Mapkit framework in order to show user current location on map(using default map i.e Apple map) . This tutorials is written in swift4. So let us dive in to the tutorial and learn how to get user current location in swift4 using CoreLocation framework.

Step 1: Create a new project using "Single view app" template and name it "UserLocationAndMapkit".

Step 2: Open "Main.storyboard" and on your ViewController's view drag "Map Kit View" i.e. MKMapView.

Get User  location in swift4 - tutorial



Step 3: Open "ViewController.swift" and create IBOutlet for "MKMapView". Also import "MapKit" framework.


Step 4: Open "Main.storyboard" and connect mapView IBOutlet to the map aka MKMapView placed on ViewController's view.

Getting user location in swift 4 - tutorial


Step 5:  Open "ViewController.swift". First import CoreLocation framework so that we can use classes to detect user current location. Below is the code that we detect user current location, we will explain the code after you went through it.


In the above code, we created instance of CLLocationManager and named it locationManager. Inside viewDidLoad function, first we set MKMapView, "showsUserLocation" property to true. This will display blue dot as current location on mapView. Then we detect if location services are enabled for the device on which our app is running, if not then control will move's to else block where we print a message you can show alert to user for better user experience.

                                           If locationServicesEnabled return true then we detect if user authorized our app to use location services or not, If authorization status comes as "denied", "restricted", "notDetermined", then we will again ask user for authorization for location. Here we requested user to allow our app to access location when app in use only  (requestWhenInUseAuthorization), you can also choose "requestAlwaysAuthorization", this permission will detect user location always in background mode too . Lastly we set location desired accuracy to best and delegate to self so that we get notified about user location update or failed, then finally we start monitoring for location updates by calling the method "startUpdatingLocation"

                                      If we get user location, then "didUpdateLocations" delegate of CLLocationManager will be gets called, providing us latitude and longitude. If it failed to get user current location then "didFailWithError" method will be invoked. In  "didUpdateLocations" method, first we stop the location manger to get user location as we need only location for first time. The we create "MKCoordinateRegion" for our mapView, so that we can zoom our map to user current location.

Note: In info.plist file, we need to set privacy policy for the location access. Keep in mind that

Getting user location in swift4 - tutorial

To simulate location on simulators

Get user location in swift4 (CoreLocation)

Where to go from here;

In this tutorial, we learned how to get user current location and display it on MKMapView in swift4 language. You can download the source code from https://goo.gl/ES48XE


Sunday, 25 February 2018

Convert pdf & images to base64 string swift 4



Convert pdf & images to base64 string swift 4


Introduction to convert PDF and images to base64 string

While developing iOS apps and if there is a need of uploading image, documents like PDF, excel doc, word doc to server(central database for our app) either we prefer byte data to be uploaded or API requires to upload documents(images, PDF,  excel, word documents) in base64 string. So we need to convert our image or PDF etc. to base64 first and then request API to upload it to server. In this tutorial, we will learn how to encode image or PDF ( or and kind of document) data to base64 string and also decode base64 string to files as per their mime types(defines type of document).  You can get more info about base64 string from https://en.wikipedia.org/wiki/Base64

Below are the code snippets for converting image to base64 string in swift and other documents like pdf etc. and vice versa.

Encoding UIImage to base64 string in swift 4 : 

 



In the above code, we have a function named "convertImageTobase64", which is accepting two parameters

1. format -  in which we want to get binary data for our image (i.e. png or jpeg)
2. image - UIImage, we want to convert to base64

In the "viewDidLoad" function, we user the "convertImageTobase64" function and get base64 string representation of UIImage in swift 4.


Decoding base64 string into UIImage in swift 4:

 



In above code snippets, we have a function that is converting base64 string to UIImage. To use it you have to to pass base64 string and it will return you UIImage object.

You can use similar function of data object to convert any other document(PDF, excel etc.) to base64 string, only you need to convert respective document to Data object.

Where to go from here

In this tutorial, we learned how to convert UIImage to base64 string in swift 4 and also convert base64 string to UIImage object using "base64EncodedString" function Data class in swift 4. You can download the source from Base64EncodingDecodingswift4.zip

Monday, 12 February 2018

Add shadow to all sides of UIView in swift 4


Add shadow to all sides of UIView in swift 4

Add shadow to all sides of UIView in swift 4

 In this tutorial, we are going to learn about adding shadow to view (UIView) in swift/ swift 4. Giving shadow to our view controls increase the visibility of app's user interface. Follow the below steps that will create shadow on all sides of UIView. 


Step 1: shadowColor: this property of CALayer, allows us to give type of color to our shadow we want to give to an UIView.

            self.cntView.layer.shadowColor = UIColor.lightGray.cgColor

Note: replace cntView, with your view object.

Step 2: shadowOpacity: this property allows us too give transparency to our view. Default value is 0.0 (complete transparent). You can set the value between 0.0 to 1.0

            self.cntView.layer.shadowOpacity = 0.5

Step3: shadowRadius: this property allows us to give radius to the shadow    

           self.cntView.layer.shadowRadius = 10.0

Step 4:shadowOffsett: offset for layer's shadow. Default is (0.0, -3.0). Default To give shadow to all sides of view, we will set this to .zero

            self.cntView.layer.shadowOffset = .zero

Step 5 : shadowPath: shape of the shadow. Default is nil, we will use UIBezierPath to set path for our shadow.
            self.cntView.layer.shadowPath = UIBezierPath(rect: self.cntView.bounds).cgPath
            self.cntView.layer.shouldRasterize = true

Complete Code:




Video tutorial to add shadow to all sides of UIView:










Tuesday, 6 February 2018

Add custom checkbox on UITableViewCell or UITableView in swift 4





Introduction to how to add custom checkbox on UITableViewCell or UITableView in swift 4

In this tutorial, we are going to learn about how can we create or add custom checkbox on UItableViewCell or UITableView in swift and perform IBAction on our custom checkbox placed on UITableViewCell or UITableView in swift 4. We will place UIButton on UITableViewCell that will act as checkbox for our UITableViewCell in UITableView using swift 4. In the end of this tutorial, we will have output as shown in below picture
Learn how to create checkbox in swift from HERE

Steps to create or add custom checkbox on UITableViewCell or UITableView

Step 1 : Create a new Xcode project and select "Single View App" template. Name  project as "addCheckBoxonTable-Tutorial".

Add custom checkbox on UITableViewCell or UITableView in swift 4

Step 2: Open "Main.storyboard" file and drag UITableView object on to the view. Then we will add constraints to UITableView so that it fits to our screen size. Please follow the steps as shown in the below picture

Add custom checkbox on UITableViewCell or UITableView in swift 4


Step 3: Now we need to add UITableViewCell to our UITableView. Drag UItableViewCell on to UITableView, added in step 2.

Add custom checkbox on UITableViewCell or UITableView in swift 4


Step 4: Select UITableViewCell and select option "Size inspector" (option will  be on right hand side of your screen) change the height to 100.0 and background color to yellow, will get it changed from "Attribute inspector". Also change the UITableView Row height to 100.0 also. Change UITableViewCell identifer ro "CheckBoxCell"

Add custom checkbox on UITableViewCell or UITableView in swift 4
Add custom checkbox on UITableViewCell or UITableView in swift 4

Add custom checkbox on UITableViewCell or UITableView in swift 4

Step 6:  Drag UILable and UIButton (this UIButton will act as checkbox for our cell in UITableview) to content view of UITableViewCell. Add constraints to both object 

  • UILable constraint: (Top = 0, Bottom = 0, Leading = 10, Trailing = 10 w.r.t. UIButton)
  • UIButton constraint: (Trailing = 10, height = 50, width = 50, align center Y to superview)
Step 7: Add images to your project. Download images from Archive-CheckBoximages.zip. Change UIButton type to custom and remove title. Set images to UIButton as follows

  1. Default state - set image Checkmarkempty
  2. Selected state - set image Checkmark

You can change state of UIButton by changing "State config" property in attribute inspector.

Step 8: Set tag for UILable  = 1 and for UIButton = 2. You will find this property under attribute inspector too.

Step 9: Open ViewController.swift. Here we will create IBOutlet for UITableView first and connect it with UITable in "Main.storyboard". Then we will write down UITableViewDatasource methods for our UITableView.  Below is the complete code for ViewController.swift file

 


In above code, we write down UITabelViewDatasource methods. numberOfRows and cellForRow,in cellForRow we get UILable using the tags we set in prototype cell, same for UIButton. Lastly, we add target to UIButton. In the selector, we set sender selected property to the opposite of its  current elected property. In more clear word if UIButton has state not selected (state other than selected state) then we make it selected and vice-versa.

Where to go from here

In this tutorial, we learned how to add checkbox on UITableViewCell in swift 4. We use UIButton to act as custom checkbox and then ad target to it in cellForRow method. You can grab the copy of source code from addCheckBoxonTable-Tutorial.zip.