Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all 595 articles
Browse latest View live

Working With Unwind Segues in Swift

$
0
0

What is Unwind Segues?

An unwind segue is also called exit segue. By using unwind segue we can navigate backward from one screen to another screen. By Unwind segue we can navigate back through multiple screens with one action.

For Implementation of unwind segue follow these steps:

1. Set Storyboard like this. Three view controllers with the navigation controller.

unwind-image1

Let’s take three view controllers — screen  1, screen 2 and 3.
We create a show segue from screen 1 to screen 2 and Present modally segue from screen 2 to screen 3. Now we can navigate forward by performing these segue. But for Backward navigation, we have to implement an unwind segue. It is very simple.

2. For this implement below action in Destination View Controller where we have to go from Third Screen. In Our Case write it in FirstVC.

@IBAction func unwindToFirstVC(segue:UIStoryboardSegue) { }

3. Now we can define an unwind segue in a storyboard.
For this , in storyboard control – drag and drop on exit icon like this.
In Presented options, select method that we implemented in First View Controller for unwind segue.

unwind-image2

4. Now take a look at Document Outline of Third VC. In that ,from bottom select an unwind segue and in the attribute, inspector gives identifier to it like this.

unwind-image3
unwind-image4

5. Now in the last step write this code for performing an unwind segue in View Controller from where we want to perform it. In our example in ThirdVC.

@IBAction func btnGoToFirstVCTapped(_ sender: UIButton) {
        performSegue(withIdentifier: "unwindSegueTo1", sender: nil)
    }

Data Passing with Unwind Segue.
For example, if we want to pass a data from ThirdVC to FirstVC then what we will do? If we want to pass a name from ThirdVC and display it in FirstVC ?
Then in unwind, an action of FirstVC write this code.

@IBAction func unwindToFirstVC(segue: UIStoryboardSegue) {
        let vc = segue.source as! ThirdVC
        label.text = " Welcome \(vc.txtField.text!) 😊 "
    }

Conclusion

By following this steps we can easily pass data to previous controller without using protocol.


Learn Modular CSS With Different Methods and Tricks

$
0
0

What is modular css?

Code which adheres to the separation of concerns can be much more confidently modified , edited, extended, and maintained because we know how far its responsibilities reach.

What is OOCSS?

Object oriented css is a css which we can modify easily , maintainable and reusable.That object can then be reused throughout a site.

What is BEM?

BEM full form is Block Element modifier. It was created in 2009 by Russian internet company Yandex who faced similar problems to Yahoo using CSS at scale.

BEM is a way to modularise development of web pages. By breaking your web interface into components. you can have your interface divided into independent parts, each one with its own development cycle.

Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end.

Block are made of smaller elements and can be modified.

Starting With BEM

Block is a component which is also the main element. Blocks are written as a class name.

For example here we will go for a contact form. So block is a form tag and for the style we can not use a

<form>

instead of that we can use is a class .form so if there are two contact forms in a website and both have a different style so we can change easily. Because classes allowed infinite reusability.

We can start from contact form so here main class is .form

.form{ /***  style *****/}

Best example is button, this is a block in which we have same button style in whole website and only color is different then we use this methodology.

.button   { padding: 15px 20px; font-size: 14px; background:#000; color: #fff;  border:0px; text-transform: uppercase;}
<button class="button" type="submit"> contact me </button>

Output:

modular-image1

Block can be a nestable one block inside which we can set another block.

Elements are children of block. Any DOM element within block can be an element. It is defined by using __ (double underscore).

Example:

.list        { width: 200px;}
.list__item { margin: 2px 0; padding: 5px; background: #333; color: #fff; list-style: none; }
<ul class="list">
    <li class="list__item">1</li>
    <li class="list__item">2</li>
</ul>

Output:
modular-image-2

Modifiers defines the appearance and behaviour of a block or an element.

For instance the appearance of the menu block may change depending on a modifier that is used on it.

Example:

.button--secondary     { background-color: #ef7573; border-radius: 50px; }
<button class="button button--secondary" type="submit">submit</button>

Output:

modular-image3

BEM naming

  1. Names are written in lowercase
  2. Words within names are separated by hyphens
  3. Elements are delimited by double underscores
  4. Modifiers are delimited by double hyphens

Here for the simple code and we reduce a CSS so that methods are used.

1) Method @mixin

Here we have used the concept based on SaaS.
Here one example for that

@mixin button { padding:15px 20px;}  
    
    .button--green{
    @inclued button;
    background-color: green;
}

In this methodology, common padding is used for all buttons but the other style will be different so we can use a different class for other style. Here is a .button–green changes background color.

2. Method use CSS attributes selector

Here another method is selector we can learn with the example

class*=’button’:not([‘button__’]){
        padding:15px 20px;
}

Here in first selector we used class*button that means it is button class with padding:15px 20px; but this is not for a button__. So that if we use a button__ with different CSS style but not add a padding so with this class we also have to add a button class also.

Benefits of Modular CSS

  1. Simplifies code and facilitates refactoring
  2. Self-documenting code
  3. Reusable code that doesn’t influence outside its own scope
  4. Naturally leads to a pattern library
  5. Predictable
  6. Maintainable
  7. Performant

Conclusion

Finally concludes that if we go through this type of methods and tricks for design a website so we can save our time . less css code so less time for run the website. and more reusable so it is easy for us.

Kotlin : Android’s future is here

$
0
0

Overview

Google has recently announced to provide first-class support to Kotlin programming language starting from Android studio 3.0. Considering the buzz which is started from Kotlin’s introduction into Android world, it seems that Kotlin is here to stay for a long time and should be given more importance.

This series of blogs is aimed to make the android developers friendly with the Kotlin.

Configuring Kotlin library with older android studios:

Android studio 3.0 comes with Kotlin support. But to get Kotlin in android studio below 3.0, we need to configure the library manually in the studio.

Steps

  1. Install Kotlin plugin by browsing JetBrains plugins in Preferences option of the Main menu and restart the studio.
  2. Now, configure Kotlin in the project from Tools menu.

Now, we can convert complete java file into kotlin file by selecting ‘Convert Java File to Kotlin File’ option from Code menu.

Farewell to findViewById

Kotlin provides a plugin for android extension which makes it much easier to access xml contents into kotlin file.
We just have to add
apply plugin: ‘kotlin-android-extensions’
in the gradle file of our app.

Also include
import kotlinx.android.synthetic.main.activity_main.*
in kotlin file, if the studio doesn’t do it automatically.
That’s it. Now we can access our xml views just by writing their ids in kotlin file.

<TextView
   android:id="@+id/tv"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Hello World!" />

TextView defined in xml with the id ‘tv’ can be accessed in kotlin file using just its id i.e. ‘tv’

tv.text = "Hello"

Conclusion

Thus, seeing a buzz about Kotlin among Android guys at Google and the excitement among the developers makes sure that Kotlin thing is here to stay and we should get adapted to it quickly

Working with CSS Grid Property

$
0
0

Overview

First of all we have to understand what is the actual structure or layout followed by CSS grid, CSS grid follows 2 dimensional structure for layout like for column and row. Where as, floex and other dom element follow the 1 dimensional structure that is column base.

From these concept the CSS grid is able to make grid with same facilities which is provided by flex structure and even more than that. Let’s understand how it works and what is the scenario behind it.

How it works?

To understand how it works we will first divide all properties into two parts:

  1. Property which is related to grid container or grid wrapper.
  2. Property which is related to grid items.

First we take some html structure for understanding further properties.

Example:

<style>
.parent { background: #d4d4d4;}
.parent > div { min-height: 40px;}
.child1 { background: #ff00d0;}
.child2 { background: #9800ff;}
.child3 { background: #2200ff;}
.child4 { background: #0083ff;}
.child5 { background: #00e9ff;}
.child6 { background: #00ff90;}
.child7 { background: #19ff00;}
.child8 { background: #ffaa00;}
.child9 { background: #ff0000;}
</style>
<div class=”parent” >
    <div class=”child-1’></div>
    <div class=”child-2’></div>
    <div class=”child-3’></div>
    <div class=”child-4’></div>
    <div class=”child-5’></div>
    <div class=”child-6’></div>
    <div class=”child-7’></div>
    <div class=”child-8’></div>
    <div class=”child-9’></div>
</div>

grid-image1

Property related to grid container or grid wrapper

Display as grid

First we set parent as display: grid; so every child behave like a grid item.
Example:

{ display: grid; }

grid-template-columns

This property is used to define how many columns are in your grid with how much width.
Example:

{ grid-template-columns: 150px 150px 150px; }

– It will create 3 columns with width of 150px.

grid-template-rows

This property is used to define how many rows are in your grid with how much height.
Example:

{ grid-template-rows: 150px 150px 150px; }

– It will create 3 rows with height of 150px.

grid-template

This property is shorthand property for column and row both in one line declaration.
Example:

{ grid-template: 150px 150px 150px / 150px 150px 150px; }

– It will create 3 rows with height of 150px, and 3 columns with width of 150px. Please make sure parameter before “/” are for rows value, and after “/” are for column value.

grid-template-areas

This property is used to define grid item location for specific column and row. Here we supposed that child elements has already set their grid-area name with their class name.
Example:

{ grid-template: 150px 150px 150px / 150px 150px 150px; 
        grid-template-areas: “child1 child2 child3”
      “child4 child5 child6”
      “child7 child8 child9”;}

– It will create 3 rows with height of 150px, and 3 columns with width of 150px. Also it sets child element as their template area name defined.

grid-gap ( grid-column-gap, grid-row-gap)

This property is used for putting gap between columns and rows. You can give different property for the individuality like only for columns using “grid-column-gap” and only for rows using “grid-row-gap”.
Example:

{ grid-gap: 15px 15px;}
{ grid-column-gap: 15px; grid-row-gap: 15px;}

– Above both styles make gap of 15px for column and rows, for “grid-gap” the first parameter are for row gap size and second for column gap size.

repeat

This property is used for making loop base continuous grid.
Example:

{ grid-template-columns: repeat(3, 150px); grid-template-rows: repeat(3, 150px); }

– Above styles make three 150px width columns and three 150px height rows.

fr

This stands for fraction of the free space of the grid. It calculates the non fixed free space of the grid.
Example:

{ grid-template-columns: 1fr 1fr 1fr;}

– Above styles make three equal size columns.

Demo Sample for grid-container property:

<style>
.parent { background: #D4D4D4; 
   display: grid; 
   grid-template: 150px 150px 150px / 150px 150px 150px;
   grid-template-areas: "child1 child2 child3" "child4 child5 child6" "child7 child8 child9";
   grid-gap: 15px 15px; } 
.child1 { background: #ff00d0; grid-area: child1;} 
.child2 { background: #9800ff; grid-area: child2;} 
.child3 { background: #2200ff; grid-area: child3;} 
.child4 { background: #0083ff; grid-area: child4;} 
.child5 { background: #00e9ff; grid-area: child5;} 
.child6 { background: #00ff90; grid-area: child6;} 
.child7 { background: #19ff00; grid-area: child7;} 
.child8 { background: #ffaa00; grid-area: child8;} 
.child9 { background: #ff0000; grid-area: child9;}
</style>
<div class=”parent” >
    <div class=”child-1”>Item 1</div>
    <div class=”child-2”>Item 2</div>
    <div class=”child-3”>Item 3</div>
    <div class=”child-4”>Item 4</div>
    <div class=”child-5”>Item 5</div>
    <div class=”child-6”>Item 6</div>
    <div class=”child-7”>Item 7</div>
    <div class=”child-8”>Item 8</div>
    <div class=”child-9”>Item 9</div>
</div>

grid-image2

justify-items ( start, center, end, stretch )

1) start: align items content on horizontally left.
Example:

{ justify-items: start; }

grid-image3

2) center: align items content on horizontally center.
Example:

{ justify-items: center; }

grid-image4

3) end: align items content on horizontally right.
Example:

{ justify-items: end;}

grid-image5

4) stretch: align items content on horizontally stretch.
Example:

{ justify-items: stretch; }

grid-image2

align-items ( start, center, end, stretch )

1) start: align items content on vertically top.
Example:

{ align-items: start; }

grid-image6

2) center: align items content on vertically middle.
Example:

{ align-items: center; }

grid-image7

3) end: align items content on vertically bottom.
Example:

{ align-items: end;}

grid-image8

4) stretch: align items content on vertically stretch.
Example:

{ align-items: stretch; }

grid-image2

justify-content (start, center, end, stretch, space-around, space-between, space-evenly)

1) start: justify content on horizontally left.
Example:

{ justify-content: start; }

grid-image2

2) center: justify content on horizontally center.
Example:

{ justify-content: center; }

grid-image9

3) end: justify content on horizontally right.
Example:

{ justify-content: end; }

grid-image10

4) stretch: justify content on horizontally stretch.
Example:

{ justify-content: stretch; }

grid-image2

5) space-around: manage grid space horizontally same size around content items.
Example:

{ justify-content: space-around; }

grid-image11

6) space-between: manage grid space horizontally same size only in between items.
Example:

{ justify-content: space-between; }

grid-image12

7) space-evenly: manage grid space horizontally same size allover grid item.
Example:

{ justify-content: space-evenly; }

grid-image13

align-content (start, center, end, stretch, space-around, space-between, space-evenly)

same as the “justify-content” only difference is the direction change, it makes all control in vertical direction.

1) start: align content on vertically top.
Example:

{ align-content: start; }

grid-image14

2) center: align content on vertically center.
Example:

{ align-content: center; }

grid-image15

3) end: align content on vertically bottom.
Example:

{ align-content: end; }

grid-image16

4) stretch: align content on vertically stretch.
Example:

{ align-content: stretch; }

grid-image14

5) space-around: manage grid space vertically same size.
Example:

{ align-content: space-around; }

grid-image17

6) space-between: manage grid space horizontally same size only in between items.
Example:

{ align-content: space-between; }

grid-image18

7) space-evenly: manage grid space horizontally same size allover grid item.
Example:

{ align-content: space-evenly; }

grid-image19

Property related to grid container items

Here all properties are related to individual grid item, so scope of the property is limited to that item only. To get better understanding we take one general Example.

Demo sample for single grid item

<style>
.parent { background: #D4D4D4; 
   display: grid; 
   grid-template-columns: [column1] 150px [column2] 150px [column3] 150px [column4];
   grid-template-rows: [row1] 150px [row2] 150px [row3] 150px [row4];
   grid-template-areas: "child1 child2 child3";
   grid-gap: 15px 15px; } 
.child1 { background: #ff00d0; grid-area: child1;} 
.child2 { background: #9800ff; grid-area: child2;} 
.child3 { background: #2200ff; grid-area: child3;}
</style>
<div style=”background: #ccc” class=”parent” >
    <div class=”child-1”>Item 1</div>
    <div class=”child-2”>Item 2</div>
    <div class=”child-3”>Item 3</div>
</div>

grid-image20

Note: line-name value does not support “grid-template” property of grid-container, it supports available grid templates for “grid-template-columns” and “grid-template-rows” properties.

grid-column-start ( line, number, name )

1) line / name: It may be number or name of column based on grid container where line-names are defined.
Example:

child1 { grid-column-start: column2; }

Above property start child1 from second number column because of parent div containing “column2” line-name at second column place.

2) number: This is based on default column numbering, this property does not rely on grid-container line-name.
Example:

child1 { grid-column-start: 2; }

Above property start child1 from second number column.

grid-column-end ( line, number, name )

1) line / name: It may be number or name of column based on grid container where line-names are defined.
Example:

{ grid-column-end: column3; }

Above property end child1 to third number column because of parent div containing “column3” line-name at third column place.

2) number: This is based on default column numbering, this property does not rely on grid-container line-name.
Example:

{ grid-column-end: 3; }

Above property end child1 to third number column.

grid-row-start ( line, number, name )

1) line / name: It may be number or name of row based on grid container were line-names defined.
Example:

{ grid-row-start: row2; }

Above property start child1 from second number row because of parent div containing “row2” line-name at second row place.

2) number: This is based on default row numbering, this property does not rely on grid-container line-name.
Example:

{ grid-row-start: 2; }

Above property start child1 from second number row.

grid-row-end ( line, number, name )

1) line / name: It may be number or name of row based on grid container where line-names are defined.
Example:

{ grid-row-end: row3; }

Above property end child1 to third number row because of parent div containing “row3” line-name at third row place.

2) number: This is based on default row numbering, this property does not rely on grid-container line-name.
Example:

{ grid-row-end: 3; }

Above property end child1 to third number row.

justify-self ( start, center, end, stretch )

It works completely same as “justify-items” property of grid-container only difference is that it is limited to only an individual item itself.

Example:

{ grid-row-end: row3; }{ justify-self: start; }, { justify-self: center;}, { justify-self: end; }, { justify-self: stretch;}

align-self ( start, center, end, stretch )

It works completely same as “align-items” property of grid-container only difference is that it is limited to only an individual item itself.

Example:

{ align-self: start; }, { align-self: center;}, { align-self: end; }, { align-self: stretch;}

Demo sample for grid-item property:

<style>
.parent { background: #D4D4D4; 
   display: grid; 
   grid-template-columns: [column1] 150px [column2] 150px [column3] 150px [column4];
   grid-template-rows: [row1] 150px [row2] 150px [row3] 150px [row4];
   grid-template-areas: "child1 child2 child3";
   grid-gap: 15px 15px; } 
.child1 { background: #ff00d0; grid-area: child1; grid-column-start: 2; grid-column-end: 3; grid-row-start: 2; grid-row-end: 3; justify-self: end; align-self: center;} 
.child2 { background: #9800ff; grid-area: child2;} 
.child3 { background: #2200ff; grid-area: child3;}
</style>
<div style=”background: #ccc” class=”parent” >
    <div class=”child-1”>Item 1</div>
    <div class=”child-2”>Item 2</div>
    <div class=”child-3”>Item 3</div>
</div>

grid-image21

Conclusion

If you have good hands on CSS and HTML, and you want to make custom grid structure using CSS rather than HTML and want to move block through CSS then definitely this the best way to do that, because you do not write any js code or does not change HTML structure code from HTML file, you only just need CSS for that. Hope it will help you!

Passport Authentication for Node.js with MongoDB

$
0
0

What is Passport?

Passport is Express-consistent authentication middleware for Node.js. Passport can be convenient and simple. It will use be any Express based web application.

Passport supports many set of strategies like,
Local Strategy :- Username (req.body.username) and
Password (req.body.password),

Single sign-on using OAuth like,
Google
e.g passport.authenticate(‘google’);
Facebook,
Twitter,
GitHub,
LinkedIn
Instagram and more…

To get started we have to install passport into our node application, we will do via npm (Node Package Manager)

Open the command prompt in Windows, Linux, or Mac Terminal. I assume that your present working directory is application in which you are going to implement the passport.

Fire the below command in command prompt:

Package :  npm install passport –save

–save :- When we create node application it is necessary to generate package.json file. Install package then write –save which means package will go inside our package.json file.

How Passport Authentication Works?

Passport authentication request is called as passport.authenticate() and also specify which strategies is to be applied. The authenticate()’s function is used to connect middleware in Express application.

Example:

app.post('/login', passport.authenticate('local'),
    function(req, res) 
    { 
      // If this function gets called, authentication was successful. 
      // `req.user` contains the authenticated user. 

      res.redirect('/users/' + req.user.username); 
   });

Passport Authentication Usage

Passport local-strategies :-

Most broadly used in website authentication for users via username and password. So this authentication is done by passport local module.

So Open terminal and fire below command,

package: npm install passport-local –save

Before authenticating request, the strategy(or strategies) used by application must be configured.

var passport = require(‘passport’),
    LocalStrategy = require(‘passport-local’).Strategy;

    passport.use(new LocalStrategy(

     function(username, password, done) {
        User.findOne({ username: username }, function(err, user) {
        if (err) { return done(err); }
         if (!user)
         {
                  return done(null, false, { message: 'Incorrect username.' });
         }

             if (!user.validPassword(password))
        {

                return done(null, false, { message: 'Incorrect password.' });
              }
        return done(null, false, { message: 'Incorrect password.' });
        });
        }
    ));

There are 300+ strategies. Find the ones you want at: passportjs.org

Form :-

A form is placed on web page and allows users to enter their own credentials and can login.

<form action="/login" method="post">
      <div>
           <label>Username:</label>
           <input type="text" name="username"/>
      </div>    
      <div>
           <label>Password:</label>
           <input type="password" name="password"/>
      </div>
      <div>
           <input type="submit" value="Log In"/>
      </div>
</form>

Sessions :-

Passport will maintain constant login sessions.
In order to have continual work with session , serialized user must be use to session for authentication, and deserialized when consecutive requests are made.

Passport does not contain any condition on how your users’ records are stored. In place of that, you provide functions to Passport which implements needful serialize and deserialize logic. In a typical application, this will be done as easily as serializing the User ID and finding the user by ID when deserialize.

passport.serializeUser(function(user, done) {
   done(null, user.id);
});

passport.deserializeUser(function(id, done) {
   User.findById(id, function (err, user) {
      done(err, user);
   });
});

Middleware :-

For the Passport used in our Express based application, it is necessary to configure it with the required middleware passport.initialize().

Your application uses persistent sessions of login so you can also use passport.session() middleware.

var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());

app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

app.use(passport.initialize());
app.use(passport.session());

Authenticate Request Or Routes:

POST method is used for submitted login form and passport using authenticate() with the use of local-strategy which will handle the login request.

app.post('/login',
    passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true })
);

successRedirect:- User enter their credential and it’s right.
FailureRedirect:- User enter their credential and it’s wrong.
FailureFlash:- Used for Messages (success message or error message)

Search all strategies :-

Strategies is available on passportjs.org
common strategies:-
Local-strategies for HTML Form,
OpenID, BrowserID
Facebook, Google, Twitter, etc..

Conclusion

That’s it ..

I personally feel to use this as it is easy to implement.

In Node.js Application passport is used for authentication purpose , but passport provides adjustability support so passport is definitely a better choice.

Passport provides robust authentication for Node.js

Kotlin : Android’s future is here – Part 2

$
0
0

Overview

This blog is written to cover basics of Kotlin in Android.

To set text of TextView:

tv.text = "Hello"

To declare various types of lists:

private var itemList = listOf<Int>(1, 2, 3)
private var itemListArrayList = mutableListOf<Int>(1, 2, 3)         //behaves like collections
private var noDuplicateList = hashSetOf<String>("azbc", "afb", "c", "c")            //avoids duplicate values
private var mapList = hashMapOf<String, Int>("a" to 1, "b" to 2, "c" to 3)          //"key" to "value"

To iterate for loop:

for ((index, value) in itemList.withIndex()) {
   Log.i("tag", "$index = $value")
}

While, do while, break and continue work as similarly as they work in java with few minor changes.

To add item in mutableList and iterate through it:

itemListArrayList.add(4)

for ((index, value) in itemListArrayList.withIndex()) {
   Log.i("tagArrayList", "$index = $value")
}

To sort hashSet and iterate through it:

for ((index, value) in noDuplicateList.toSortedSet().withIndex()) {         
   Log.i("tagHashSet", "$index = $value")
}

To get value from hashMap using a key:

Here, a is the key.

Log.i("tagHashMap", mapList["a"].toString())

Conclusion

These are just a few techniques among many for using collections in Kotlin. Make sure to check them out.

Kotlin : Android’s future is here – Part 3

$
0
0

Overview

Activity, Fragment & Dialog Fragment

This blog is aimed to learn how to open dialog fragment and fragment from activity.

Opening activity from activity

I’ll explain this procedure using splash screen demo.

Handler is used to perform a task after specific period of time.
I have used startActivity( ) method to start another activity (MainActivity).

Handler().postDelayed({
   val i = Intent(this, MainActivity::class.java)
   startActivity(i)
   finish()
}, 3000)

Opening dialog fragment from activity

First of all create a class for dialog fragment and extend it.

class DialogFrag : DialogFragment() {
   private var text: TextView? = null
   private var array = ArrayList<String>()
   private var rv: RecyclerView? = null
   override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
       var view: View? = inflater?.inflate(R.layout.activity_main2, container, false)
       return view!!
   }

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setStyle(STYLE_NORMAL, R.style.AppTheme)
   }
}

Now, create object of this class in MainActivity and call show( ) method to show the dialog fragment.

bt?.setOnClickListener() { view -> DialogFrag().show(fragmentManager, "dialFrag") }

Here, bt is a button which opens the dialog fragment when clicked.

Notes:-

  1. Here, lambda function is used with setOnClickListener( ) (written inside { }). This is the correct way to call anonymous method instead of calling it via an inner class which is used in java.
  2. getters and setters aren’t used. Instead of these, properties are used. For eg. fragmentManager instead of getFragmentManager( ).

Opening fragment from activity

First of all, take a frame in activity’s layout.

<FrameLayout
   android:id="@+id/frame"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Now, create a class for fragment and extend it.

class Fragment1 : Fragment() {
   override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
       val view: View? = inflater?.inflate(R.layout.activity_main2, container, false)
       return view
   }
}

Now, from activity, begin fragment transaction and replace the frame with the fragment.

fragmentManager.beginTransaction()?.replace(R.id.frame, Fragment1() as Fragment)?.addToBackStack("frag")?.commit()           //chaining

Finally, commit the transaction.

Note:-
Here, (?.) is used multiple times in same line. This is called chaining. If any (?.) operator returns null then the complete expression will be null. This is one of the disadvantages of Kotlin.

Conclusion

This shows how adaptable Kotlin is for Android Developers. It’s almost similar to java with just a few changes.

Kotlin : Android’s future is here – Part 4

$
0
0

Overview

Recycler View

RecyclerView is a boon to Android developers when it comes to handling a huge amount of data in list form.

RecyclerView with Kotlin

We need to add compile com.android.support:recyclerview-v7:+ into our app-level gradle file

Then, we have to add recycler view in our xml file

<android.support.v7.widget.RecyclerView
   android:id="@+id/rv"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Now, create a row file with name row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">

   <TextView
       android:id="@+id/tv"
       android:layout_width="match_parent"
       android:layout_height="45dp" />
</LinearLayout>

We have to create an adapter which will process the data and will display it in recycler view.

class MyAdapter(var names: ArrayList<String>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
   override fun onBindViewHolder(holder: ViewHolder, position: Int) {
       holder.title.text = names.get(position)
   }

   override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
       var view = LayoutInflater.from(parent?.context).inflate(R.layout.row, parent, false)
       return ViewHolder(view)
   }

   override fun getItemCount(): Int {
       return names.size
   }

   class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
       var title: TextView = view.findViewById(R.id.tv) as TextView

       init {

       }
   }

}

Finally, we have to set adapter to recycler view in main activity and also set the layout manager for recycler view.

rv = view?.findViewById(R.id.rv) as RecyclerView
array.add("abc")
array.add("def")
array.add("ghi")
array.add("jkl")
array.add("mno")
rv?.layoutManager = LinearLayoutManager(activity)
rv?.adapter = MyAdapter(array)

Conclusion

Recycler view is a ‘must to know’ concept in recycler view. This solves many problems of list view. Hence, if you are new to android, get used to using it. This will help you in a lot of ways.


Use of px, em, rem units in css, which one I have to use and when?

$
0
0

Overview

Many people are confused to work with these three units together for the same design. The main reason behind it is the lack of the unit measurement of individual.

First we will have basic understanding of these units.

  1. Px : px is unit of the screen.
  2. Em : em is unit that contains parental element of pixel size.
  3. Rem : rem is unit that contains root element (default) of pixel size.
  4. Confusion between em & rem : which one should I use, and when?
  5. Nested Case : where hierarchy on property contain different units measurement.
  6. Combine Example : which unit contain which value at the same time

We can use these units for multiple property scenario like font-size, padding, margin, position property especially for measurement properties.

Px

Px are known as non linear angular element, which is measured by screen size of the device. Px are fixed element that works for the individual element where they are defined.

Example:

div { font-size: 10px; padding: 10px; }

This will set font size as 10px and set padding from every side as 10px.

Em

Em are dependant on parental property sizing. This is not fixed element because it depends on measurement so when the parental measurement change, the value of the em change.

Example:

div { font-size: 10px; padding: 10em; }

This will set font size as 10px and set padding as 100px from every side, because it takes measurement from font-size property where any value taken is set as 1em i.e (10px = 1em so 10em = 10px X 10 = 100px).

Rem

Rem depends on default browser or html property sizing. This is not fixed element because it depends on measurement so when the parental measurement change, the value of the rem is changed. You can change the default browser font size from settings of that particular browser.

Example:
Suppose browser default font-size is 14px.

div { font-size: 10px; padding: 10rem; }

This will set font size as 10px and set padding as 140px from every side, because it takes measurement from browser default font-size property where any value taken is set as 1em i.e (14px = 1rem so 10rem = 14px X 10 = 140px).

Confusion between em & rem

Actual question regarding use of this unit arises is that, which unit is used when specially in case of “em” and “rem”. For this be specific which unit you make default value and for which element you have dynamic measurement.

  • To setup default font size all over the webview where you don’t need to change size. If element is nested, then “rem” is preferable.
  • To setup dynamic measurement, if font-size decrease then element padding or margin also decrease, and then you have to select “em”.

Nested Case

In nested case, only one element is useful that is “em”. If any requirement arise like, child element’s font size or padding are half of the parental element, then “em” is useful.

Example:

div.parent { font-size: 10px; }
div.parent div.child { font-size: 0.5em; }

This will set parent font size as 10px and set child font-size as 5px because it takes measurement from parent font-size property where any value is taken & set as 1em i.e (10px = 1em so 0.5em = 10px / 2 = 5px).

Combine Example

In following example we assume that the default browser font size is 14px. So how does it effect in all three units.

Example:

div.parent { font-size: 10px; padding: 10em; margin: 10rem;}
div.parent div.child { font-size: 0.5em; padding: 10em; margin:10rem}

– For ( div.parent )
Font-size is = 10px.
Padding from every side is ( 10px = 1em so 10em X 10px ) = 100px
Margin from every side is ( 14px = 1rem so 10rem X 14px ) = 140px

– For ( div.child )
Font-size is ( 0.5em = 10px / 2) = 5px.
Padding from every side is ( 5px = 1em so 10em X 5px ) = 50px
Margin from every side is ( 14px = 1rem so 10rem X 14px ) = 140px

The turning point of the child css is font-size, because it inherits from parent element where parent element’s font size is 10px and child element is set as 0.5em so it is divided by 2 and result is set as child font size.

Padding is dependent on font size of the current element’s font size so it converts 1em in 5px because now font size is set as 5px.

Only margin is constant in both cases because it is directly inherited from root element as 14px font-size which is unchanged so it will be 140px in both case.

Conclusion

In the end i think that, to overcome these confusion we have to just make things simple which elements are based on browser or html base and which are based on media device so the selection of measurement tool becomes very easy.

I hope it will help you to overcome at least little bit from confusion of these three unit.

Design your map in Mapbox and integrate it in Unity

$
0
0

Overview

This article explains you the procedure to design a map in Mapbox and then implement the Mapbox services in Unity3D.

What is Mapbox?

Mapbox is one of the best location data platform targeted for mobile and web applications.
You can use these services in Unity and create your own location and map based games.

Maps and location data optimized for Unity. Written from the ground up in C#, the Mapbox Unity SDK unlocks global data to generate custom 3D worlds, power location lookup, and incorporate traffic-based directions in your next Unity project.

The best part is that you can use the services for free until you cross the 50,000 monthly active mobile platform users mark.

First of all you have to sign up to get your account in Mapbox.
Now, Let’s design a map in Mapbox Studio and then use it in Unity.

Sign in and navigate to the Mapbox Studio to create a new basic Map Style.

You can see your map. We will change its look and feel by altering values in different Layers.

Scroll down in Layers section -> click on background -> change it’s color value to hsl(112, 80%, 71%)

Similarly change color values of below layers.
You will need colors for roads,buildings,land and water.

“background” - hsl(112, 80%, 71%)
“water” - hsl(190, 93%, 54%)
“road_major” - hsl(165, 39%, 45%)
“road_minor” - hsl(165, 43%, 56%)
“landuse_park” - hsl(141, 43%, 53%)
“bridge_major” - hsl(165, 56%, 33%)
“tunnel_major” - hsl(165, 38%, 31%)
“building” - hsl(240, 23%, 31%)

Change the Opacity field value of “building” layer to value 0.3

Fiddle around the color and opacity value of various layers in order to achieve your desired map look.

Your map should now look something like this.

Now let us add borders to our roads.
We will duplicate the “road_major” layer and rename it to “road_major border”.
“road_major” layer will stay on top of the “road_major border”.
Set the widths of both the layers in order to give it a border effect.

Do a similar procedure for “road_minor” layer.

Fiddle around the values to get your desired road border effect.
While increasing the width values make sure that the roads don’t overlap over each other.

For now, your road-border should look like this.

Now let us add a texture to the water layer.
Download the water.svg texture file and drag and drop this texture file into mapbox studio.
Duplicate the “water” layer. Add the water texture to the Pattern field with opacity of 0.1

You may replicate the same process for roads & buildings using road.svg and building.svg file.

Make additional adjustments to the map to get your desired look and then publish the map.

Congratulations! You successfully created a simple map style for your location-based game. You can now use this style with Mapbox Unity SDK, GL JS,iOS SDK, Android SDK .

We will now use this awesome map in Unity.

Integration of Mapbox with Unity

Pre-requisites
1.) Unity 5.6.0f3 or later.
2.) Download the Mapbox Unity SDK.

Create a new project in Unity and import the Mapbox Unity SDK package.
Create a new scene and save it.
Search for the “Attribution” prefab inside “Assets/Mapbox/Prefabs” and add it to our scene.

Before integrating the sdk we will get a new access token.
Navigate to Tokens and click “Create a new token” button.
Select scopes:list & styles:list and click “Generate” button.
Copy the new token and open Unity.
Select Mapbox > Configure to add your new access token.

Below are few scripts/assets from the SDK that we will be using to generate our Map in Unity.

  • Abstract Map
  • Abstract Tile Provider
  • Location Provider Factory
    • Device Location Provider
    • Editor Location Provider
    • Transform Location Provider
  • Map Visualizer
    • Flat Terrain Factory
    • Map Image Factory
    • Vector Tile Factory
  • Build Map At Location
  • Position With Location Provider
  • Player Tile Provider

Add this PlayerTileProvider.cs script to your project

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mapbox.Unity.Utilities;
using Mapbox.Unity.Map;
using Mapbox.Utils;
using Mapbox.Map;

public class PlayerTileProvider : AbstractTileProvider {

    [SerializeField]
    private Transform locationMarker;

    [SerializeField]
    private AbstractMap map;

    [SerializeField]
    private int _visibleBuffer;

    [SerializeField]
    private int _disposeBuffer;

    private bool _initialized = true;
    private Vector2d _currentLatLng;
    private UnwrappedTileId _currentTile;
    private UnwrappedTileId _cachedTile;

    void Start() {
        Initialize (map);
    }

    internal override void OnInitialized() {
    }

    float _elapsedTime;

    [SerializeField]
    float _updateInterval;

    private void Update() 
    {
        if ( !_initialized ) return;

        _elapsedTime += Time.deltaTime;
        if (_elapsedTime >= _updateInterval)
        {
            _elapsedTime = 0f;
            _currentLatLng = locationMarker.position.GetGeoPosition ( map.CenterMercator, map.WorldRelativeScale );

            _currentTile = TileCover.CoordinateToTileId ( _currentLatLng, map.Zoom );

            if ( !_currentTile.Equals ( _cachedTile ) ) 
            {
                for ( int x = _currentTile.X - _visibleBuffer; x <= (_currentTile.X + _visibleBuffer); x++ ) 
                {
                    for ( int y = _currentTile.Y - _visibleBuffer; y <= (_currentTile.Y + _visibleBuffer); y++ ) 
                    {
                        AddTile ( new UnwrappedTileId ( map.Zoom, x, y ) );
                    }
                }
                _cachedTile = _currentTile;
                Cleanup ( _currentTile );
            }
        }
    }

    private void Cleanup( UnwrappedTileId currentTile ) {
        var count = _activeTiles.Count;
        for ( int i = count - 1; i >= 0; i-- ) {
            var tile = _activeTiles[i];
            bool dispose = false;
            dispose = tile.X > currentTile.X + _disposeBuffer || tile.X < _currentTile.X - _disposeBuffer;
            dispose = dispose || tile.Y > _currentTile.Y + _disposeBuffer || tile.Y < _currentTile.Y - _disposeBuffer;

            if ( dispose ) {
                RemoveTile ( tile );
            }
        }
    }
}

Go through this video for further steps.

That’s it.
Finally you can see that your map is loaded inside Unity.
You can replace the cube with a 3D Character.

Build the project to a phone and you can see the map loaded in your phone.
Make sure the location services and internet connection is enabled.
Go for a walk and you will see the cube following your path in the Map.

Congratulations!
You should now be capable of integrating Mapbox maps inside Unity and you can use it for your next location & map based game.

In the next tutorial, I will explain the procedure to add various custom dataset points in our map and then use the same points to the map loaded in Unity.

Meanwhile, If you have an idea for your next game and need any help in executing your concept, we will be more than happy to make it a reality. Contact Us

Things You Don’t Know about iPhone 8/8 Plus/X

$
0
0

Overview

Apple recently announced three new iPhones named 8/8 Plus and X among them X is more special as it is created to celebrate iPhone’s 10th anniversary and it is first iPhone with full screen display. Here are few things and facts that you may not know about all these new iPhones

Battery

  • It is quite surprising that iPhone 8/8 Plus have lower batteries compared to iPhone 7/7 Plus.
  • Although Apple’s new A11 Bionic chip in iPhone 8/8 Plus may help save battery.
  • Phil Schiller (Apple Senior Vice President of Worldwide Marketing) has said in Apple’s official September 2017 event that iPhone 8/8+ battery life will be 2 hours more than iPhone 7/7+

iPhone 8/8 Plus Faster Than iPhone X


(image reference from here)

  • Apple’s latest and greatest 10th anniversary phone iPhone X will be bit slow compared to iPhone 8/8 Plus because of larger display.
  • iPhone X is designed with all screen display containing higher ppi (458 ppi) compared to iPhone 8/8 Plus.
  • iPhone X has 2436×1125 resolution with HDR support.
  • When it comes to contrast ratio, it is seriously huge number 1,000,000:1 with super retina display.

So by above points (especially ppi) we can say that iPhone X need more power to render pixels on its large screen. Apple A11 Bionic chip is much faster and efficient to handle all of this, plus iPhone X has 3GB RAM to take care of multitasking which will help keep apps up in background. There will be no difference in daily usage of phone but with heavy task load we may see slight performance difference.

Turn Off iPhone X

  • In all other iPhones press and holding power button shows the slide to power off screen but in iPhone X it will open siri.
  • One way to turn off iPhone X is by going to Setting -> General -> Shut Down
  • In rare case when iPhone freeze and do not respond, at that time it require Force Restart commonly known as Hard Restart to get back in responsive mode.
  • Solutions for above issue is press and keep holding power and volume down button simultaneously, and keep holding it until display turns off (approx 10 seconds)

No More Back Labels

  • Jony Ive (Chief Design Officer) hates printing marking labels of Regulatory Stamping and FCC Label on back of iPhone.
  • Manufactures are still required to show Regulatory and FCC Label, but its already there in Setting -> General -> Regulatory.
  • So in new iPhones say goodbye to those ugly labels.

150 Times Faster

  • Here is cool fact, iPhone 8/8 Plus/X are 150 times faster than original iPhone, whereas iPhone 7/7 Plus are 120 times faster than original iPhone
  • So we can say that, this year iPhones are 25% faster compared to last year models

iPhone X Display

  • Here is a major difference in display, Display Resolution of iPhone X is 15 times higher than original iPhone and that in just 10 years

3 Year Of A11 Bionic Chip

  • With an exclusive interview with Mashable, Phil Schiller and Johny Scrouji (Senior Vice President of Hardware Technologies) reveal the journey of A11 Bionic chip
  • They have started working for A11 chip, when they shipped iPhone 6 with A8 chip
  • Click Here for full interview.

New Wallpaper in iPhone X

  • New wallpapers exclusively for iPhone X are shown on keynote and advertisements.
  • These are actually series of new wallpaper that will be 3D touch interactable or live wallpapers exclusively for the iPhone X (something that Apple did not tell us)

Pricing Lineup

  • I am very curious about Apple iPhone’s pricing history, Most iPhone have stayed at relatively same price when released but chart went high with price of iPhone X
  • Cost to manufacture single iPhone X is $412(estimated)

Heaviest iPhone Made Ever

(above chart show weight in grams)

  • iPhone X : 6.14 ounces = 174 grams
  • iPhone 8 : 5.22 ounces = 148 grams
  • iPhone 8 Plus : 7.13 ounces = 202 grams (Heaviest ever)

Thickness

  • Apple was working to make their every iPhone thinner than previous one
  • But from this year iPhones are actually growing in thickness
  • As of now iPhone 6 (released in 2014) is the thinnest iPhone

FaceID

Craig Federighi (senior vice president of software engineering) has revealed some key FaceID details like following :

  • Time out for FaceID is 48 hours, currently it’s 8 hours on Touch ID.
  • Now how much secure FaceID is, it is also revealed that three facial features are required to make FaceID work which are Eyes, Nose, Mouth. So if you are obstruct with any of these, FaceID will not work (full article here)
  • FaceID work through sunglasses, so if you are worried about having to take your sunglasses off every time you unlock your device, no worries. FaceID is able to penetrate the lenses on most sunglasses to scan eye.

Rating IP67

  • iPhone 8/8 Plus/X are not waterproof but water resistant. It has same rating as the iPhone 7/7 Plus which are not waterproof either
  • You can take it and dip in water real quick but don’t keep it there for long, It certainly don’t have the same rating as the Samsung Galaxy S8

Add custom dataset points to Mapbox map and integrate them in Unity

$
0
0

Overview

This article explains you the procedure to add custom dataset points in Mapbox map and then implement those points in Unity3D.

Please go through this first if you are not aware of designing Mapbox maps and integrating them in Unity.

We will use Mapbox datasets and tilesets to add points to our map.

What is Mapbox Dataset?

A dataset is an editable collection of GeoJSON features hosted in your Mapbox account. Datasets can be created, modified, and deleted in Mapbox Studio or through the Datasets API.

What is Mapbox Tileset?

Tilesets are a format for displaying your dataset in maps.
Tilesets are lightweight collections of vector data that are optimized for rendering in a map and are not editable.

Let us create a dataset and use it in our map.

Go to Datasets section.
Click New dataset to create a dataset.
Click the “Draw a point” icon and add a point in your map.
Once you are done adding and editing features in your dataset, open Tilesets section.
Create a new tileset from your dataset.

Now open Datasets section again and add a new point in your map.
Click on “Export” and now you can see that you can update your connected tileset directly.

Open Tilesets section and add your tileset to a map style in the Mapbox Studio style editor.
Create the new layer and now you can see your points in your map.

Go through this video to understand the steps to add dataset and tileset to our map

Let us integrate the tileset points inside Unity.

Now that we have created the Enemy tileset from our dataset.
Copy the Enemy tileset map id.
We will use this map id inside Unity.

Open Unity and click on Mapbox -> Clear Caches.

Now go through this video to understand the steps to add dataset points to Unity.

Finally, we can see that the two points that we added in our dataset is now accessible inside Unity.

Congratulations!
You can now add more points of different types to your dataset and then use those types as per your wish.
You are now capable of integrating Mapbox maps inside Unity.

If you have an idea for your next game or If you need any help in executing your concept, we will be more than happy to make it a reality. Contact Us.

Kotlin : Android’s future is here – Part 5

$
0
0

Overview

Retrofit

In this blog, we will concentrate on very important aspect in Android – API integration.
We will use Retrofit library in this demo and the response of the API is observed using RxJava.
Let’s get started.

Including libraries in gradle file:

After configuring Kotlin in the project, we will need 4 libraries:-

compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"
compile "io.reactivex.rxjava2:rxandroid:2.0.1"

Making model to store data:

We will use GitHub API – https://api.github.com/search/users.
So the model class according to its response will be,

data class User(
        val login: String,
        val id: Long,
        val url: String,
        val html_url: String,
        val followers_url: String,
        val following_url: String,
        val starred_url: String,
        val gists_url: String,
        val type: String
)

data class Result(val total_count: Int, val incomplete_results: Boolean, val items: List<User>)

Make a class called Results and include data as mentioned above.
data keyword specifies that this class is supposed to hold data and such classes automatically override functions like toString( ) and hashCode( ).

Making interface to interact with the API from our project:

interface GithubApiService {
    @GET("search/users")
    fun search(@Query("q") query: String): Observable<Result>
}

As shown above, I have used @GET annotation as the API uses GET method with parameters:- q for query and few other optional parameters like page and per_page for pagination purpose.

We can also see search/users as parameter of @GET annotation. It is the url that attaches with base url which is https://api.github.com/.

There is a method called search( ) which takes parameters (query) as the argument and returns Observable. Observable is from RxJava which stores the result if response is obtained successfully otherwise it displays the error.

Note:- Here, we are aiming to get response from GitHub by passing Java as our query

Calling API and obtaining response:

In MainActivity.kt, build the retrofit object as shown below.

val retrofit = Retrofit.Builder()               .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
                .baseUrl("https://api.github.com/")
                .build()

Here, we have used GsonConverterFactory with retrofit and we also have to add CallAdapterFactory as we are using RxJava. This factory will enable us to use functions like observeOn, subscribeOn, subscribe etc. which are used to get the response stored in Observable in proper way.

Now, create an instance of the interface using retrofit.

val apiInterface = retrofit.create(GithubApiService::class.java)

Using this variable, we can access the function defined in interface.

apiInterface.search("Java")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe({

                    result ->
                    Log.d("Result", "${result.total_count} results found")
                }, { error ->
                    error.printStackTrace()
                })

Here, we have passed Java as the argument.

ObserveOn( ) will be used to access main thread of the app and manage changes made to the UI of app as the API is called (if required).
SubscribeOn( ) will work in back-end on another thread which is used to call the API.
With subscribe( ), we can obtain result of the response.

D/Result: 30895 results found
Here, we have obtained the above result in the console.

Conclusion

API integration is another very important topic in Android World and out of many ways to achieve this integration, Retrofit is the best in my opinion.

Kotlin encourages to use RxJava along with retrofit. This will help us to receive the response of API in proper way than the usual way i.e. by AsyncTask.

Bootstrap 4: Create Five, Seven, Ten and Eleven equal width grid with margin.

$
0
0

Overview

Working with new version of bootstrap [ Bootstrap 4 (Beta) ], again I find that there were no any specific grid structure for Five, Seven, Ten and Eleven equal width grid and put grid offset (margin) same as in previous versions of bootstrap.

As a web designer for some design with five and seven grid structure, I have decided to create some custom stylesheet for this type of grid system with similar offset structure, and it really works well with new bootstrap [ version 4 ] structure and also without affecting their grid system. Following is some instruction on how to use this grid structure. Hope this stylesheet is helpful if you have similar design structure.

Following are some points that you must take a look at,

  • Link “bootstrap4-custom-grid.css” just below your bootstrap.css
  • Every class of custom grid indicates individual width for specific div in which you put that class.
  • It will also work with specific resolution as bootstrap like “sm, md, lg, xl” as well as “extra small”.

How to use classes for the responsive grid as well as Margin-Left (ml), Margin-Right (mr).

Extra-small device:
col-“Cell Number”, ml-“Cell Number”, mr-“Cell Number”
Small device:
col-sm-“Cell Number”, ml-sm-“Cell Number”, mr-sm-“Cell Number”
Medium device:
col-md-“Cell Number”, ml-md-“Cell Number”, mr-md-“Cell Number”
Large device:
col-lg-“Cell Number”, ml-lg-“Cell Number”, mr-lg-“Cell Number”
Extra Large device:
col-xl-“Cell Number”, ml-xl-“Cell Number”, mr-xl-“Cell Number”

You can use “Cell number” as cell5, cell7, cell10, cell11.

Tabular class indication for grid class and grid margin:

For Example width for grid number 5, 7, 10, 11:
col-cell5, col-sm-cell5, col-md-cell5, col-lg-cell5
col-cell7, col-sm-cell7, col-md-cell7, col-lg-cell7
col-cell10, col-sm-cell10, col-md-cell10, col-lg-cell10
col-cell11, col-sm-cell11, col-md-cell11, col-lg-cell11

For Example margin for grid number 5, 7, 10, 11:
Margin Left:
ml-cell5, ml-sm-cell5, ml-md-cell5, ml-lg-cell5, ml-xl-cell5
ml-cell7, ml-sm-cell7, ml-md-cell7, ml-lg-cell7, ml-xl-cell7
ml-cell10, ml-sm-cell10, ml-md-cell10, ml-lg-cell10, ml-xl-cell10
ml-cell11, ml-sm-cell11, ml-md-cell11, ml-lg-cell11, ml-xl-cell11

Margin Right:
mr-cell5, mr-sm-cell5, mr-md-cell5, mr-lg-cell5, mr-xl-cell5
mr-cell7, mr-sm-cell7, mr-md-cell7, mr-lg-cell7, mr-xl-cell7
mr-cell10, mr-sm-cell10, mr-md-cell10, mr-lg-cell10, mr-xl-cell10
mr-cell11, mr-sm-cell11, mr-md-cell11, mr-lg-cell11, mr-xl-cell11

Five Grid width & margin

Grid with margin-left and margin right

<div class="row">
        <div class="col-cell5"><div>col-cell5</div></div>
        <div class="col-cell5 ml-cell5 mr-cell5"><div>col-cell5</div></div>
        <div class="col-cell5"><div>col-cell5</div></div>
</div>

Seven Grid width & Margin Example

Grid with margin-left and margin right

<div class="row">
        <div class="col-cell7"><div>col-cell7</div></div>
        <div class="col-cell7"><div>col-cell7</div></div>
        <div class="col-cell7 ml-cell7 mr-cell7"><div>col-cell7</div></div>
        <div class="col-cell7"><div>col-cell7</div></div>
        <div class="col-cell7"><div>col-cell7</div></div>
</div>

Ten Grid width & Margin Example

Grid with margin-left and margin right

<div class="row">
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10 ml-cell10 mr-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
        <div class="col-cell10"><div>col-cell10</div></div>
</div>

Eleven Grid width & Margin Example

Grid with margin-left and margin right

<div class="row">
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11 ml-cell11 mr-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
        <div class="col-cell11"><div>col-cell11</div></div>
</div>

Hope you find it useful !

Kotlin : Android’s future is here – Part 6

$
0
0

Overview

View Pager

This blog is about implementing view pager in Android using Kotlin.
Most of the implementation of view pager in Kotlin is just same as that of in Java.

View Pager without fragments

Including view pager in xml

<android.support.v4.view.ViewPager
   android:id="@+id/view_pager"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

Row/Page file of View Pager

Here, we have a text view in center of page which will display the page number as we swipe the view pager

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

   <TextView
       android:textSize="30dp"
       android:gravity="center"
       android:text="1"
       android:id="@+id/pageFile_tv"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</LinearLayout>

Implementing Pager Adapter

class CustomAdapter(private val con: Context) : PagerAdapter() {

   private val layoutInflater: LayoutInflater

   init {
       layoutInflater = LayoutInflater.from(con)

   }

   override fun getCount(): Int {
       return 5
   }

   override fun isViewFromObject(view: View, `object`: Any): Boolean {
       return view === `object`
   }

   override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
       container.removeView(`object` as View)
   }

   override fun instantiateItem(container: ViewGroup, position: Int): Any {
       val view = layoutInflater.inflate(R.layout.page_file, container, false)
       view.pageFile_tv.text = "${position + 1}"
       container.addView(view)
       return view
   }
}

The name of this adapter is CustomAdapter. It works exactly in same way as that written in Java. There is just a change of language.

Assigning adapter to View Pager in MainActivity

class MainActivity : AppCompatActivity() {

   private var customAdapter: CustomAdapter? = null

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)
       init()
       setAdapter()

   }

   internal fun init() {
       customAdapter = CustomAdapter(baseContext)
   }

   internal fun setAdapter() {
       view_pager!!.adapter = customAdapter
   }
}

Note:- internal keyword behaves like default in java. It is a good practice to assign internal to functions requiring no access modifier as by default they will be final.

View Pager with fragments

Including view pager in xml

<android.support.v4.view.ViewPager
   android:id="@+id/actMain_viewPager"
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

Create the fragments that you want to display inside the view pager

Here, we will display different colored background for each fragment in view pager.
I’ll show one fragment here, for instance.

XML file:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/colorAccent"
   android:orientation="vertical">

   <FrameLayout
       android:id="@+id/frag1_frame"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</LinearLayout>

Kotlin file:-

class Frag1 : android.support.v4.app.Fragment() {

   override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
       val view = inflater!!.inflate(R.layout.frag1_layout, container, false)
       return view
   }
}

Implementing FragmentStatePager Adapter

class CustomPageAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {

   override fun getItem(position: Int): android.support.v4.app.Fragment {

       var fragment: android.support.v4.app.Fragment? = null
       when (position) {
           0 -> fragment = Frag1()
           1 -> fragment = Frag2()
       }

       return fragment!!
   }

   override fun getCount(): Int {
       return 2           //no of cases/fragments
   }

}

Assigning adapter to View Pager in MainActivity

class MainActivity : AppCompatActivity() {

   private var customPageAdapter: CustomPageAdapter? = null

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       init()
       setAdapter()
   }

   internal fun init() {
       customPageAdapter = CustomPageAdapter(supportFragmentManager)

   }

   internal fun setAdapter() {
       actMain_viewPager!!.adapter = customPageAdapter
   }
}

Conclusion

View Pagers are necessary for the apps where tab layouts are used. They simplify the interface making it user friendly. Coding view pagers in Kotlin is not much different than in Java.


Bootstrap 4 (Beta) Pros & Cons

$
0
0

Overview

Bootstrap is HTML, CSS and JS responsive framework. Now here comes the bootstrap 4 with beta version. It has been updated a lot than Bootstrap version 3. Anything that gets updated have both pros and cons.

Topics

  1. Pros
  2. Cons

Pros:

  • Bootstrap 4 is using flexbox which will increase the flexibility to arrange the elements. It has been moved away from float.
  • It has been switched from using “px” to “rem”.
  • It has been switched from “less” to “sass”.
  • It has added dozens of new utility classes for common CSS property-value pairs.
    For Example:
    1. To apply rounded border to any element you need to simply add “rounded-circle” class to it.
    2. To vertically center align the element you need to add “align-middle” class.
  • It has revised grid system media queries breakpoints and ensured that the columns are divided into 12.
    // Extra small devices (portrait phones, less than 576px)
    // No media query since this is the default in Bootstrap// Small devices (landscape phones, 576px and up)
    @media (min-width: 576px) { … }// Medium devices (tablets, 768px and up)
    @media (min-width: 768px) { … }// Large devices (desktops, 992px and up)
    @media (min-width: 992px) { … }// Extra large devices (large desktops, 1200px and up)
    @media (min-width: 1200px) { … }
  • As it is supporting flexbox, it provides support for horizontal and vertical alignment.
  • Box-sizing value has been changed from “content-box” to “border-box”.

Cons:

  • It will be difficult for those who are not so adaptable to accept that bootstrap has changed the classes and media query breakpoint.
  • It does not provide support to non responsive usage.
  • It also does not support IE8, IE9 and iOS 6
  • Removed -xs infix. It mean that “col-xs-6” in version 3 becomes “col-6” in version 4.
  • Dropped the online customiser

Kotlin : Android’s future is here – Part 7

$
0
0

Overview

Tab Layout

This blog is about implementing tab layout in Android using Kotlin.

Tab Layout with view pager

Including tab layout & view pager in xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.MainActivity">

   <android.support.v7.widget.Toolbar
       android:id="@+id/toolBar"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@color/colorPrimary" />

   <android.support.design.widget.TabLayout
       android:id="@+id/tabLayout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:tabMode="fixed" />

   <android.support.v4.view.ViewPager
       android:id="@+id/viewPager"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</LinearLayout>

Create the fragments that you want to display inside the view pager when tab is selected

Here, we will display different colored background for each fragment in view pager.
I’ll show one fragment here, for instance.

XML file:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/colorAccent"
   android:orientation="vertical">

   <FrameLayout
       android:id="@+id/frag1_frame"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</LinearLayout>

Kotlin file:-

class Frag1 : android.support.v4.app.Fragment() {

   override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
       val view = inflater!!.inflate(R.layout.frag1_layout, container, false)
       return view
   }
}

Implementing FragmentStatePager Adapter

class ViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

   private val fragments = ArrayList<Fragment>()
   private val tabNames = ArrayList<String>()

   fun addFragmentTabName(fragment: Fragment, tabName: String) {

       fragments.add(fragment)
       tabNames.add(tabName)

   }

   override fun getItem(position: Int): Fragment {
       return fragments[position]
   }

   override fun getCount(): Int {
       return fragments.size
   }

   override fun getPageTitle(position: Int): CharSequence {            
       return tabNames[position]
   }
}

Here, I have used 2 arrayLists; one for storing fragments and 1 for storing names of tabs.

To display names of tabs on tab selection, getPageTitle( ) method is overridden in adapter and it returns name of the tab at selected position.

To display fragment on tab selection, getItem( ) method is overridden in adapter which returns the fragment at selected position.

Code in MainActivity.kt

class MainActivity : AppCompatActivity() {

   private var viewPagerAdapter: ViewPagerAdapter? = null

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       init()

       viewPager!!.offscreenPageLimit = 3         //upto 3 off screen pages will not get destroyed. default is 1
       setSupportActionBar(toolBar)
       passFragmentsIntoAdapter()
       setAdapter()
       setIconsInTabLayout()
   }

   internal fun init() {
       viewPagerAdapter = ViewPagerAdapter(supportFragmentManager)

   }

   internal fun passFragmentsIntoAdapter() {            
       viewPagerAdapter!!.addFragmentTabName(Frag1(), "Frag1")
       viewPagerAdapter!!.addFragmentTabName(Frag2(), "Frag2")
       viewPagerAdapter!!.addFragmentTabName(Frag3(), "Frag3")
   }

   internal fun setAdapter() {
       viewPager!!.adapter = viewPagerAdapter
       tabLayout!!.setupWithViewPager(viewPager)
   }

   internal fun setIconsInTabLayout() {         //should be called after setting adapter and tab layout
       //tab titles can also be set here using setText
       tabLayout!!.getTabAt(0)!!.setIcon(R.mipmap.ic_launcher)
       tabLayout!!.getTabAt(1)!!.setIcon(R.mipmap.ic_launcher)
       tabLayout!!.getTabAt(2)!!.setIcon(R.mipmap.ic_launcher)
   }

}

Tab Layout without view pager

Including tab layout & a frame layout in xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.MainActivity">

   <android.support.design.widget.TabLayout
       android:id="@+id/actMain_tabLayout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="#336699" />

   <FrameLayout
       android:id="@+id/actMain_frame"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_weight="1" />
</LinearLayout>

Create the fragments that you want to display when tab is selected

Here, we will display different colored background for each fragment.
I’ll show one fragment here, for instance.

XML file:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/colorAccent"
   android:orientation="vertical">

   <FrameLayout
       android:id="@+id/frag1_frame"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
</LinearLayout>

Kotlin file:-

class Frag1 : android.support.v4.app.Fragment() {

   override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
       val view = inflater!!.inflate(R.layout.frag1_layout, container, false)
       return view
   }
}

Code in MainActivity.kt

class MainActivity : AppCompatActivity() {
   private var fragmentTransaction: FragmentTransaction? = null

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.activity_main)

       addFirstFrag()
       designTabLayout()

       actMain_tabLayout!!.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

override fun onTabSelected(tab: TabLayout.Tab?) {            setCurrentTabFragment(actMain_tabLayout!!.getSelectedTabPosition())
}
           override fun onTabUnselected(tab:TabLayout.Tab?){            
}
      override fun onTabReselected(tab:TabLayout.Tab?) {
}
})

}

   internal fun addFirstFrag() {
       fragmentTransaction = fragmentManager!!.beginTransaction()

       fragmentTransaction!!.replace(R.id.actMain_frame, Frag1())
       fragmentTransaction!!.addToBackStack("")
       fragmentTransaction!!.commit()
   }

   internal fun designTabLayout() {
      actMain_tabLayout!!.addTab(actMain_tabLayout!!.newTab().setIcon(R.mipmap.ic_launcher).setText("1"))
       actMain_tabLayout!!.addTab(actMain_tabLayout!!.newTab().setIcon(R.mipmap.ic_launcher).setText("2"))
       actMain_tabLayout!!.addTab(actMain_tabLayout!!.newTab().setIcon(R.mipmap.ic_launcher).setText("3"))

   }

   internal fun addFrag(fragment: Fragment) {
       fragmentTransaction = fragmentManager!!.beginTransaction()

       fragmentTransaction!!.replace(R.id.actMain_frame, fragment)
       fragmentTransaction!!.addToBackStack("")
       fragmentTransaction!!.commit()
   }

   internal fun setCurrentTabFragment(pos: Int) {
       when (pos) {
           0 ->
               addFrag(Frag1())
           1 ->
               addFrag(Frag2())
           2 ->
               addFrag(Frag3())
       }
   }
}

First, we have to design the tab layout before loading fragments in frame layout i.e. setting icon and text for each tab.

Then, I have loaded 1st fragment in the frame layout.

Finally, I have used addOnTabSelectedListener( ) to detect the selected tab and then on selection of the tab, I have loaded the respective fragment in the frame.

Conclusion

Tab layouts are in fashion now-a-days. We see them in facebook, whatsapp and other such giant apps. Hence, it is a good idea to learn to code tab layouts in Kotlin because it will be a must requirement in future projects.

iOS Proactive Suggestions

$
0
0

Overview

Introduce new ways to increase user engagement with your app.System suggest your app to users at appropriate times.

You can provide information about what users do in your app, which helps the system promote your app in additional places, such as

  • Keyboard with QuickType suggestions,
  • Maps and CarPlay,
  • The app switcher,
  • Siri interactions,
  • The lock screen

There are some ways to increase user engagement, such as:

NSUserActivity

NSUserActivity is eyes of operating system, an NSUserActivity object provides a lightweight way to capture the state of your app and put it to use later.

iOS 10 and later in NSUserActivity class added mapItem attribute, that provide location information that can be used in other contexts.

You can use the new text-based address component properties in CSSearchableItemAttributeSet, such as thoroughfare and postalCode, to fully specify locations to which the user may want to go.

App Switcher Proactive Suggestion using handoff

You must need to use same icloud account in your devices and bluetooth of your device need to on

var continuedActivity: NSUserActivity?

// call this method when you want to suggest your app to another device 
   func createUserActivity(company:Company,index:Int) {
        userActivity = NSUserActivity(activityType: "Yudiz.ProactiveSuggetions.viewDetails")
        userActivity?.userInfo = ["name":company.name, "address":company.address,"link":company.url]
        userActivity?.title = "\(index)"
        userActivity?.needsSave = true
        userActivity?.becomeCurrent()
    }

// this method is called when another device opens app from app switcher suggestion 
    override func restoreUserActivityState(_ activity: NSUserActivity) {
        continuedActivity = activity
        super.restoreUserActivityState(activity)
    }

// this method is called when app is successfully updated useractivity 
    override func updateUserActivityState(_ activity: NSUserActivity) {

        super.updateUserActivityState(activity)
    }

// this method is called when app is opened from proactive suggestion user get suggestion when user unlock device.(left bottom of device)
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        NSLog("Received a payload via handoff : %@",userActivity.title ?? "nil")
                return true
    }

Here Info.plist file add key for activityType

Location Suggestions

Provide map item to be promoted throughout the system, This will automatically populate the contentAttributeSet property with all available location information, including geo coordinates, text address components, phone numbers, etc.
Provide just enough information in the userInfo dictionary to be able to restore state

a. Stoplight Search

var arrCompany = [Company]()
    override func viewDidLoad() {
        super.viewDidLoad()

        arrCompany.append(
            Company(name:"Apple",
                    address:"Cupertino, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Apple_Inc",
                    logo:#imageLiteral(resourceName: "apple"))
        )

        arrCompany.append(
            Company(name:"Google",
                    address:"Googleplex, Mountain View, California, U.S",
                    url:"https://en.wikipedia.org/wiki/Google",
                    logo:#imageLiteral(resourceName: "google"))
        )

        arrCompany.append(
            Company(name:"Microsoft",
                    address:"Albuquerque, New Mexico, United States",
                    url:"https://en.wikipedia.org/wiki/Microsoft",
                    logo:#imageLiteral(resourceName: "microsoft"))
        )

        arrCompany.append(
            Company(name:"Samsung",
                    address:"Seocho District, Seoul, South Korea",
                    url:"https://en.wikipedia.org/wiki/Samsung",
                    logo:#imageLiteral(resourceName: "samsung"))
        )

        arrCompany.append(
            Company(name:"Amazon",
                    address:"Seattle, Washington, U.S",
                    url:"https://en.wikipedia.org/wiki/Amazon.com",
                    logo:#imageLiteral(resourceName: "amazon"))
        )

        arrCompany.append(
            Company(name:"Facebook",
                    address:"Menlo Park, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Facebook",
                    logo:#imageLiteral(resourceName: "facebook"))
        )

        arrCompany.append(
            Company(name:"Flipkart",
                    address:"Bangalore, Karnataka, India",
                    url:"https://en.wikipedia.org/wiki/Flipkart",
                    logo:#imageLiteral(resourceName: "flipkart"))
        )

        arrCompany.append(
            Company(name:"Yahoo",
                    address:"Sunnyvale, California, U.S.",
                    url:"https://en.wikipedia.org/wiki/Yahoo!",
                    logo:#imageLiteral(resourceName: "yahoo"))
        )

setupSearchableContent()

    }

func setupSearchableContent() {
        var searchableItems = [CSSearchableItem]()

        for record in arrCompany {

            let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
            searchableItemAttributeSet.title = record.name
            searchableItemAttributeSet.thumbnailData = UIImagePNGRepresentation(record.logo)
            searchableItemAttributeSet.contentDescription = record.address
            searchableItemAttributeSet.keywords = [record.name,record.address]
            let searchableItem = CSSearchableItem(uniqueIdentifier: "com.yudiz.SpotIt.\(record.name)", domainIdentifier: "company", attributeSet: searchableItemAttributeSet)
            searchableItems.append(searchableItem)

        }

        // this method index your data to eligible for spotlight suggestion  
        CSSearchableIndex.default().indexSearchableItems(searchableItems) { (error) -> Void in
            if error != nil {
                print(error?.localizedDescription ?? "nil")
            }
        }

    }

Address component properties in CSSearchableItemAttributeSet. It’s also recommended that you supply a value for the namedLocation property, so that users can view the name of the location, and the phoneNumbers property, so that users can use Siri to initiate a call to the location

b. Location Suggestions and Keyboard with QuickType suggestions

func getLocation(company:Company) {
        let request = MKLocalSearchRequest()

        request.naturalLanguageQuery = company.name // Location name you want to search for given lat,long 
        request.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(23.0225, 72.5714), 1600, 1600)

        MKLocalSearch(request: request).start { (response, error) in
            guard error == nil else { return }
            guard let response = response else { return }
            guard let exampleMapItem = response.mapItems.first else { return }

            let activity = NSUserActivity(activityType: "Yudiz.ProactiveSuggetions.viewDetails")
            activity.title = exampleMapItem.name
            activity.mapItem = exampleMapItem
            self.userActivity = activity

            activity.isEligibleForHandoff = true
            activity.isEligibleForSearch = true
            activity.isEligibleForPublicIndexing = true

            // Set delegate
            activity.delegate = self
            self.userActivity?.becomeCurrent()

        }
    }

override func updateUserActivityState(_ activity: NSUserActivity) {
              var userInfo = [String: AnyObject]()
        userInfo["placemark"] = NSKeyedArchiver.archivedData(withRootObject: (activity.mapItem.placemark)) as AnyObject?
        if let url = activity.mapItem.url {
            userInfo["url"] = url as AnyObject?
        }
        if let phoneNumber = activity.mapItem.phoneNumber {
            userInfo["phoneNumber"] = phoneNumber as AnyObject? 
        }

        activity.userInfo = userInfo

        // Provide additional searchable attributes.
        activity.contentAttributeSet?.supportsNavigation = true
        activity.contentAttributeSet?.supportsPhoneCall = true
    }

If users view a location described on your app, the system can suggest the same location when users switch to Maps Application

How to customize your app icon?

$
0
0

Overview

iOS 10.3 allows you to change your app icon programmatically. We can change our app icon programmatically.

Let’s get started.

Tool Used: Xcode 9.1, Swift 4+

Step 1: Setup Project

Create new Xcode project.

Write name of your project, we have use SwitchingAppIcon. (Make sure that you choose swift language) and Click on Next button.

Create two icons @2x and @3x for the iPhone, we named it as appicon_1@2x and appicon_1@3x. Add them in their appropriate places in the assets folder.

We can add alternative icons but not into the assets folder.

Step 2: Register Alternative icons

Register these alternative icons in our Info.plist. Add this to your Info.plist file.

For iPhone App

<key>CFBundleIcons</key>
    <dict>
        <key>CFBundleAlternateIcons</key>
        <dict>
            <key>appicon_2</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>appicon_2</string>
                </array>
                <key>UIPrerenderedIcon</key>
                <false/>
            </dict>
            <key>appicon_3</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>appicon_3</string>
                </array>
                <key>UIPrerenderedIcon</key>
                <false/>
            </dict>
        </dict>
        <key>CFBundlePrimaryIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string></string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>

Make sure alternative icons are named without @2x and @3x prefix.

For iPad App

<key>CFBundleIcons~ipad</key>
    <dict>
        <key>CFBundleAlternateIcons</key>
        <dict>
            <key>appicon_2</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>appicon_2</string>
                </array>
                <key>UIPrerenderedIcon</key>
                <false/>
            </dict>
            <key>appicon_3</key>
            <dict>
                <key>CFBundleIconFiles</key>
                <array>
                    <string>appicon_3</string>
                </array>
                <key>UIPrerenderedIcon</key>
                <false/>
            </dict>
        </dict>
        <key>CFBundlePrimaryIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string></string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>

Step 3: Write some code

Create 3 buttons in our storyboard which will change between our icons.

Connect them in your ViewController and add this code to change app icons

// MARK:- Actions
extension ViewController{
    @IBAction func btnTapAction(_ sender: UIButton){
        // If false, alternate icons are not supported for the current process.
        if UIApplication.shared.supportsAlternateIcons {
            var alternateIconName: String? = nil
            switch sender.tag {
            case 2:
                // Change App icon 2
                alternateIconName = "appicon_2"
                break
            case 3:
                // Change App icon 3
                alternateIconName = "appicon_3"
                break
            default:
                break
            }

            // Pass `nil` to use the primary application icon. 
            UIApplication.shared.setAlternateIconName(alternateIconName)
        }
    }
}

Step 4: Test

Press on App icon 1 to set default App icon.

Press home button to see result.

Press on App icon 2 to set appicon_2 icon

Press home button to see result.

Press on App icon 3 to set appicon_2 icon

Press home button to see result.

Note:
Be careful to use a unique key name for each alternate icon

For more reference
Apple Developer Documentation

Data Scraping in Android using Jsoup(Java HTML Parser)

$
0
0

Overview

Jsoup Iterate all elements of HTML illustration demonstrates to choose and repeat all elements of HTML document utilizing Jsoup.

Jsoup gives select technique which acknowledges CSS style selectors to choose the elements.

For choosing every one of the elements of HTML page, you have to pass “*” as the selector

“*” selector chooses every one of the elements of the HTML document. You would then be able to repeat over elements utilizing for circle.

Step 1 : HTML Source Code

We will use http://www.yudiz.com/blog/ for a data scraping of this webpage.

Author Name HTML Code:-

<span class="vcard author post-author test">
<a href="http://www.yudiz.com/author/sandeep-joshi/">
Sandeep Joshi
</a>
</span>

Blog Upload Date HTML Code:-

<span class="post-date updated">November 24, 2017</span>

Blog Title HTML Code:-

<div class="post-title">
<h2 class="entry-title" itemprop="headline">
<a href="http://www.yudiz.com/how-to-customize-your-app-icon/">
How to customize your app icon?
</a>
</h2>
</div>

Note:- For Scraping you must have to find the unique HTML element tag for necessary field otherwise you should have to find by some other HTML element if the same HTML element is used for other purposes.

Step 2 : Android Source Code

Permissions to be needed in Manifest.xml :-

<uses-permission android:name="android.permission.INTERNET" />

Gradle Dependencies to be add :-

dependencies {
   implementation 'org.jsoup:jsoup:1.11.2'
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.jsoupdemo.MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/act_recyclerview"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

   </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

row_data.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_margin="5dp">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical">

       <TextView
           android:id="@+id/row_tv_blog_title"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_margin="5dp"
           android:textStyle="bold" />

       <TextView
           android:id="@+id/row_tv_blog_author"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_margin="5dp" />

       <TextView
           android:id="@+id/row_tv_blog_upload_date"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_margin="5dp" />
   </LinearLayout>
</android.support.v7.widget.CardView>

MainActivity.java

public class MainActivity extends AppCompatActivity {

   private ProgressDialog mProgressDialog;
   private String url = "http://www.yudiz.com/blog/";
   private ArrayList<String> mAuthorNameList = new ArrayList<>();
   private ArrayList<String> mBlogUploadDateList = new ArrayList<>();
   private ArrayList<String> mBlogTitleList = new ArrayList<>();

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       new Description().execute();

   }

   private class Description extends AsyncTask<Void, Void, Void> {
       String desc;

       @Override
       protected void onPreExecute() {
           super.onPreExecute();
           mProgressDialog = new ProgressDialog(MainActivity.this);
           mProgressDialog.setTitle("Android Basic JSoup Tutorial");
           mProgressDialog.setMessage("Loading...");
           mProgressDialog.setIndeterminate(false);
           mProgressDialog.show();
       }

       @Override
       protected Void doInBackground(Void... params) {
           try {
               // Connect to the web site
               Document mBlogDocument = Jsoup.connect(url).get();
               // Using Elements to get the Meta data
               Elements mElementDataSize = mBlogDocument.select("div[class=author-date]");
               // Locate the content attribute
               int mElementSize = mElementDataSize.size();

               for (int i = 0; i < mElementSize; i++) {
                   Elements mElementAuthorName = mBlogDocument.select("span[class=vcard author post-author test]").select("a").eq(i);
                   String mAuthorName = mElementAuthorName.text();

                   Elements mElementBlogUploadDate = mBlogDocument.select("span[class=post-date updated]").eq(i);
                   String mBlogUploadDate = mElementBlogUploadDate.text();

                   Elements mElementBlogTitle = mBlogDocument.select("h2[class=entry-title]").select("a").eq(i);
                   String mBlogTitle = mElementBlogTitle.text();

                   mAuthorNameList.add(mAuthorName);
                   mBlogUploadDateList.add(mBlogUploadDate);
                   mBlogTitleList.add(mBlogTitle);
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
           return null;
       }

       @Override
       protected void onPostExecute(Void result) {
           // Set description into TextView

           RecyclerView mRecyclerView = (RecyclerView)findViewById(R.id.act_recyclerview);

           DataAdapter mDataAdapter = new DataAdapter(MainActivity.this, mBlogTitleList, mAuthorNameList, mBlogUploadDateList);
           RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
           mRecyclerView.setLayoutManager(mLayoutManager);
           mRecyclerView.setAdapter(mDataAdapter);

           mProgressDialog.dismiss();
       }
   }
}

DataAdapter.java

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.MyViewHolder> {

   private ArrayList<String> mBlogTitleList = new ArrayList<>();
   private ArrayList<String> mAuthorNameList = new ArrayList<>();
   private ArrayList<String> mBlogUploadDateList = new ArrayList<>();
   private Activity mActivity;
   private int lastPosition = -1;

   public DataAdapter(MainActivity activity, ArrayList<String> mBlogTitleList, ArrayList<String> mAuthorNameList, ArrayList<String> mBlogUploadDateList) {
       this.mActivity = activity;
       this.mBlogTitleList = mBlogTitleList;
       this.mAuthorNameList = mAuthorNameList;
       this.mBlogUploadDateList = mBlogUploadDateList;
   }

   public class MyViewHolder extends RecyclerView.ViewHolder {

       private TextView tv_blog_title, tv_blog_author, tv_blog_upload_date;

       public MyViewHolder(View view) {
           super(view);
           tv_blog_title = (TextView) view.findViewById(R.id.row_tv_blog_title);
           tv_blog_author = (TextView) view.findViewById(R.id.row_tv_blog_author);
           tv_blog_upload_date = (TextView) view.findViewById(R.id.row_tv_blog_upload_date);
       }
   }

   @Override
   public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View itemView = LayoutInflater.from(parent.getContext())
               .inflate(R.layout.row_data, parent, false);

       return new MyViewHolder(itemView);
   }

   @Override
   public void onBindViewHolder(MyViewHolder holder, final int position) {
       holder.tv_blog_title.setText(mBlogTitleList.get(position));
       holder.tv_blog_author.setText(mAuthorNameList.get(position));
       holder.tv_blog_upload_date.setText(mBlogUploadDateList.get(position));
   }

   @Override
   public int getItemCount() {
       return mBlogTitleList.size();
   }
}

Step 3 : Test

Viewing all 595 articles
Browse latest View live