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

Adding an existing project to GitHub using the command line

$
0
0

Github

GitHub is a Git repository hosting service, web-based. It offers all of the distributed version control and SCM (source code management) functionality of Git as well as adding its own features. It provides several collaboration and access control features such as bug tracking, feature requests, task management. GitHub offers both plans for free repositories on the same account  which are commonly used to host open-source software projects and private repositories.

There are two ways to add project in Github as following:

  1. Directly  from Android Studio.
  2. Using the Command line (Terminal).

Today, We will learn about add project to Github using the command line (Terminal).

Steps for adding an existing project to Github using the command line:

  1. First of all Login og Sign Up on Github.
  2. After that you will see the plus sign on the right corner of your screen. From that select New Repository.
    screen-1
  3. Then you will see the new window , Where you can enter your repository name like TestRepository.
    screen-2
  4. After that your repository will be created. Now you can see Quick setup Window in front of you.  Here you can see your HTTPS and SSH url.
    screen-3
  5. Now open you Terminal.
  6. Then after you have to change your current working directory to your local project directory.  For that you have to fire “cd” command with your project directory path.
    Shortcut:
    • Type “cd” command and directly drag and drop your project directory to the terminal. You will see the full path of your local project directory.
    • Type “cd” command and just copy your project directory and paste after “cd” command. You will get full path of your local project directory.
      Then you will redirect to your local project directory.
      screen-4
  7. Now initialize your local project directory as a Git repository using “init” command.
    screen-5
  8. Now add all your files to the new local project directory.
    screen-6
  9. After adding all files, You have to commit that staged files by particular tag just for your remind like “test commit”.
    screen-7
  10. From the Quick Setup Window  copy Repository URL.
    screen-8
  11. In terminal add your repository URL for the remote repository, Where your local project repository will we pushed. This command will sets new remote for your repository.
    screen-9
  12. Now push all changes of your local project repository to the Github. It will push all code to the Github.
    screen-10

Finally, your local repository placed in Github. Now you can see your project in your Github repository.


Mobile World Congress 2017

$
0
0

Mobile World Congress 2017

Barcelona is a beautiful, artistic city in Spain. Known for its’ architectural allure, Barcelona has made an immense development in the field of business world. Perceiving this growth, the city of Barcelona hosts the annual Mobile World Congress 2017, organised by GSMA.

MWC 2017 Logo

Every year, the mobile related industries and IT companies from around the world are invited to attend this event where they get a chance to provide a global platform to market their business. Yudiz Solutions Pvt. was invited to this prestigious event. As soon as our company heard about it, the excitement level knew no bounds. Our CEO  and Business Development Head represented our company at MWC 2017. The event was held from 27th February to 2nd March.

Pepper Robot

Samsung VR Experience

The event had diverse companies and businesses including  Mobile app development, app marketing, app monetization, app analytics, IT products and many others, that had established themselves as growing mobile companies. Moreover, the futuristic concepts like IOT and VR were the highlights of the event.

Our Business Development Head was interviewed by App Futura, a renowned platform that helps companies and individuals to find a right app development partner. The quick questionnaire session was conducted to get an idea of our company Yudiz, the clientele, the range of services that we offer, expertise of the company and the work-force environment. Our Development head summarised the company work style and projects accomplished so far.

Our representatives mingled with the personnel from other companies while exchanging significant information amongst one another and expanding the business circle. The event was indeed an exposure to the wide business world with an opportunity to market one’s own business. It gave the new and young entrepreneurs to accelerate their startup businesses. The event gave the established company such as ours to market the services.

MWC 2017 was a great way to widen the business world horizons, with a chance to meet the who’s who of the IT and business world. Being conducted in Barcelona, was just an addition to the excitement!

Startup Meeting

At MWC Barcelona

meet-client-1

meet-client-3

How to create Five, Seven, Ten, Eleven equal width grid with offset in twitter bootstrap

$
0
0

Overview

Working with bootstrap I realize that there were no any specific grid structure for Five, Seven, Ten and Eleven equal width grid and offset.

As a web designer I was recently facing some design with five and seven grid structure so I have decided to create some custom stylesheet for this type of grid system with similar offset structure, and it really works well with bootstrap structure and also without affecting their grid system. Following is some instruction how to use this grid structure. Hope this stylesheet is helpful for your similar design structure.

Following are some points that you must take a look at

  • Put “custom-bootstrap-grid.css” under your bootstrap.css
  • Every class of custom grid indicates individual width for specific div in which you put that class.
  • It will come with custom padding from both sides as bootstrap grid padding system. [ Ex: 15px ]
  • It will also work with specific resolution as bootstrap like “xs, sm, md, lg”.

How to use classes for the responsive grid as well as offset

Extra-small device:
cust-xs-grid-“Grid Number”, cust-xs-offset-grid-“Grid Number”

Small device:
cust-sm-grid-“Grid Number”, cust-sm-offset-grid-“Grid Number”

Medium device:
cust-md-grid-“Grid Number”, cust-md-offset-grid-“Grid Number”

Large device:
cust-lg-grid-“Grid Number”, cust-lg-offset-grid-“Grid Number”

You can use “Grid number” as 5, 7, 10, 11.

grid-table

For Example Grid number 5, 7, 10, 11:

cust-xs-grid-5, cust-sm-grid-5, cust-md-grid-5, cust-lg-grid-5
cust-xs-grid-7, cust-sm-grid-7, cust-md-grid-7, cust-lg-grid-7
cust-xs-grid-10, cust-sm-grid-10, cust-md-grid-10, cust-lg-grid-10
cust-xs-grid-11, cust-sm-grid-11, cust-md-grid-11, cust-lg-grid-11

Five Grid width & offset Example

Grid

<div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">1</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">2</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">3</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">4</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">5</div></div>
    <div class="clearfix"></div>
</div>

5-grid

Offset

<div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">1</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5 cust-xs-offset-grid-5 cust-sm-offset-grid-5 cust-md-offset-grid-5 cust-lg-offset-grid-5"><div class="common-div">2</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">3</div></div>
    <div class="cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5"><div class="common-div">4</div></div>
    <div class="clearfix"></div>
</div>

5-offset

Seven Grid width & offset Example

Grid

<div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">6</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">7</div></div>
     <div class="clearfix"></div>
</div>

7-grid

Offset

<div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7 cust-xs-offset-grid-7 cust-sm-offset-grid-7 cust-md-offset-grid-7 cust-lg-offset-grid-7"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-7 cust-sm-grid-7 cust-md-grid-7 cust-lg-grid-7"><div class="common-div">6</div></div>
     <div class="clearfix"></div>
</div>

7-offset

Ten Grid width & offset Example

Grid

<div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">6</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">7</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">8</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">9</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">10</div></div>
     <div class="clearfix"></div>
</div>

10-grid

Offset

<div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10 cust-xs-offset-grid-10 cust-sm-offset-grid-10 cust-md-offset-grid-10 cust-lg-offset-grid-10"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">6</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">7</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">8</div></div>
     <div class="cust-xs-grid-10 cust-sm-grid-10 cust-md-grid-10 cust-lg-grid-10"><div class="common-div">9</div></div>
     <div class="clearfix"></div>
</div>

10-offset

Another way for “Grid number” as 10:

You can also make by taking cust-xs-grid-5 and under that you have to take div with class=row and under that pair of two col-xs-6, col-sm-6, col-md-6, col-lg-6 classes as your relevant resolutions, and then it will be divide into 10 equal width grid.

For example:

<div class=”cust-xs-grid-5 cust-sm-grid-5 cust-md-grid-5 cust-lg-grid-5”>
    <div class=”row”>
        <div class=”col-xs-6 col-sm-6 col-md-6 col-lg-6”></div>
        <div class=”col-xs-6 col-sm-6 col-md-6 col-lg-6”></div>
    </div>
</div>

Eleven Grid width & offset Example

Grid

<div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">6</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">7</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">8</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">9</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">10</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">11</div></div>
     <div class="clearfix"></div>
</div>

11-grid

Offset

<div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">1</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11 cust-xs-offset-grid-11 cust-sm-offset-grid-11 cust-md-offset-grid-11 cust-lg-offset-grid-11"><div class="common-div">2</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">3</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">4</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">5</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">6</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">7</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">8</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">9</div></div>
     <div class="cust-xs-grid-11 cust-sm-grid-11 cust-md-grid-11 cust-lg-grid-11"><div class="common-div">10</div></div>
     <div class="clearfix"></div>
</div>

11-offset

Here is a demo link: Click Here

Hope you find it useful !

Generate documentation using ‘Jazzy’ for Swift

$
0
0

Overview

In this blog we are going to learn about how to automatically generate documentation for your project, framework, pod or library written in Swift matching Apple’s official reference documentation without writing a single line of code outside Xcode.

Documenting the code is an extremely important task for every developer. It’s an actually part of development process. I would agree that writing proper and comprehensive documentation for every single properties (variables and constants), methods, functions, classes, structs, enums, protocols, extensions, and any other code structure or entity you can think of or anything else that exists in a project is not an easy job. Writing the proper documentation for:

  1. Detail description of the properties, methods and classes, also highlight specific conditions, provide some notes, gives usage example of code, cases or requirements for your functions that have to be noted somewhere.
  2. Gives description of input (parameters) values and output (returns) values of your method.
  3. Description are written in easy word to understand for other developers and also for you. When you revisit a project months or years after initial implementation you remember everything without forgotten.

For this produce professional documentation using Jazzy, which is an open source project developed by Realm Developers. Documentation generated in bunch of linked HTML, CSS and JS files which looks exactly like the Apple documentation.

Markdown syntax for commenting

Before producing professional documentation for your code, we must to know the common commenting Markdown Syntax basics. If you already know about it, you’re good to go ahead, and skip this steps.

Markdown syntax is using special characters for formatting a text, for adding resources (like links and images) and for having special blocks of text (code blocks, usage example, order and unorder list). Those characters are easy to remember. Here’s a list of the most common Markdown syntax:

  1. #text#: It makes the text a header, same use of the <H1>tag in HTML. Double “#” characters will result in <H2>header tag in HTML, and so on until the <H6>header tag in HTML.
  2. **text**: It turns the text into bold.
  3. *text*: It turns the text into italics.
  4. * text: It creates an unordered list of items, also known as a bullet list (space character must be between the asterisk and the text). You can also use either the “+” or the “-” character instead of the asterisk. To wrap list items with hanging indent use up to three spaces after the asterisk (or any of the other two) symbol.
  5. 1. text: It creates an ordered list of items (numbered list).
  6. [linked text](http://myblog-url.com): It turns the text into hyperlink.
  7. > text: It turns the text into a blockquote.
  8. If you want to add indentation, same use of the <pre> and </pre> tag in HTML, you need to add set of 4 space characters or 1 tab character.
  9. If you don’t want to mess with spaces or tabs, then include your code in backticks characters. For example,
    `var property`

    will result to this: var property
  10. Create blocks of code is to add four backtick symbols, then start to write your code in new line, and after the last line of code add another set of four backticks.

How to write comment in Swift?

In swift there are specific rules that should be followed when documenting any kind of entity. Each row shall start with 3 slashes(///) like the shown below:

/// Comment texts write here for each row

or everything should be included in a code block like the shown below:

/**
Comment texts write here 
*/

In swift there is support double slashes (//) will result in a commented line too, but they’ll be ignored by Xcode and they would not render any documentation at all.

Here I write comments for my own created “Alert” Class.

/// Generates user event driven alerts.
/// It used to displays an alert message to the user. It is extended from `UIAlertController`. This class replace the `UIAlertView` class for displaying alerts.
class Alert: UIAlertController {
}

Multiline comments for methods with Markdown syntax for parameter description, usage example, block of codes and notes.

/**
Displays alert over passed view controller with title, message and buttons. - Parameters:
- inController: InController over which the alert is presented. Should use self, or provide view controller name.
- title: Title of the alert
- message: Main message presented in the alert
- userAction: UserAction optional parameter, it invoked when user tap on particular button in
alert.
## Usage Example: ## ````
Alert.showAlertView(inController: presentingViewController, title: "Title of the Alert", message: "Main message presented in the alert")
````
**Note :** If you wants to handle user tap action then you must be use userAction parameter */
class public func showAlertView(inController: UIViewController, title: String, message: String, userAction: ((String) -> ())? = nil) {
}

You can find a lot of information about Markdown syntax on the web and your first search will return back to you several related results. You’ll find excellent sources to read more about Markdown syntax example from here and here.

Code documentation previewed and accessed in xCode

The code documentation you write in Xcode can be previewed and accessed in Xcode by two different ways:

  1. By placing the cursor in the property, method or class name, and opening the Quick Help Inspector like.Screen_Shot_1
  2. By Option/Alt-Clicking to the name of a property, method, class, etc. The Quick Look preview will pop up right above or below the name like.Screen_Shot_2

Generating professional documentation

About Jazzy Tool

Jazzy is great open source tool that can produce an Apple-style documentation for your code written in Swift. Actually, Jazzy creates a bunch of HTML pages that can contain every part of your code along with the documentation you’ve written in it. It’s command-line utility/tool and it’s easy to be used.

How to install Jazzy Tool?

How Jazzy it works, I’m not interested in; please visit its page on the GitHub and you’ll find all the information you need actually an easy process:

  1. Open your Terminal by Spotlight searching or from Dock.
  2. Type a command: [sudo] gem install jazzy.
  3. Enter your system password.
  4. Wait for while done process.

If the installation fails, make sure you update your RubyGem to the latest version as the package itself requires Ruby 2 or greater. Some El Capitan or later mac os users had issues with gem so if you’re one of them instead of typing gem install in your terminal, type the following:

  1. Type a command : sudo gem install -n /usr/local/bin jazzy.
  2. Enter your system password.
  3. Wait for while done process.

If you’re missing some other dependencies such as CocoaPods installing jazzy will also pull those updates as well. The reason why the first command does not work is because of the new System integrity protection feature introduced in El Capitan which restricts even administrators from writing to /usr/bin. After the installation process is completed, you’re ready to use Jazzy documentation tool.

Demo app description

To make it easy to you to try Jazzy out, I’ve prepared a small app that you can download here. It contains source code and generated professional documentation what we were discuss earlier. It’s a really, simple and not that useful at the same time app. App will display only AlertView for user information, accept user input/action and displaying.

Now ready to generate documentation

I hoping that you’ve downloaded the app by now, let’s see how Jazzy is used. Initially, Navigate to your xCode project’s root folder in terminal using the cd command:

cd path_to_project_root_folder

More about Jazzy tool, you can see more options are use with Jazzy by typing:

jazzy --help

You should see something like this:
Screen_Shot_3

Additionally, if you don’t have the latest Swift version and you see no results by Jazzy, then you can simply specify the Swift version of your xCode supports by adding another parameter to the above:

jazzy --swift-version 2.3 --min-acl internal

Now type jazzy and require options, and sit back to wait until Jazzy finishes its tasks. However, this will not include classes or other structures that have not been marked as public. Therefore, if you want to include everything, just type this:

jazzy --min-acl internal

Vipuls-iMac:JazzyDemo yudiz$ j  azzy --min-acl internal Running xcodebuild
Parsing ViewController.swift (1/3)
Parsing AppDelegate.swift (2/3)
Parsing Alert.swift (3/3)
building site
jam out ♪♫ to your fresh new docs in `docs`

Navigate to your Xcode project root folder and you should see a completely new folder called docs. Inside there are a bunch of HTML, JS and CSS files but you should simply open index.html and the entire documentation should popup. Example is given below:

Screen_Shot_4

MySQL Vs MySQLi Vs PDO

$
0
0

Overview

To understand the difference between MySQL, MySQLi and PDO first we need to understand all of it individually.

There are two or three PHP APIs for accessing the MySQL database depending on PHP version. The user who uses PHP 5, they can choose MySQL which is deprecated, Mysqli or PDO. The user who uses PHP 7, they have only two options either MySQL or PDO.

MySQL

This is the main original extension designed to develop PHP applications that interact with a MySQL database. It provides procedural interface but it is deprecated as of PHP 5.5.0 and has been removed as of PHP 7.0.0. So, I suggest to use either MySQLi or PDO extension.

MySQLi

The i stands for Improved. The MySQLi is an extension to work with MySQL version 4.1.13 or newer. MySQLi is introduced with PHP Version 5.0 and MySQLi takes advantage of the newer features of MySQL 5.

PDO

PDO stands for PHP Data Objects. It is a database access layer providing a uniform method of access to multiple databases. PDO supports twelve different databases which are as below:

  1. CUBRID
  2. MS SQL Server
  3. Firebird/Interbase
  4. IBM
  5. Informix
  6. MySQL
  7. MS SQL Server
  8. Oracle
  9. ODBC and DB2
  10. PostgreSQL
  11. SQLite
  12. 4D

PDO sadly has one disadvantage, it does not allow you to use all of the advanced features that are available in the latest versions of MySQL server. Consider example, PDO does not allow you to use MySQL’s support for Multiple Statements.

Difference between MySQL, MySQLi and PDO

The main differences of three extensions are as below.

MySQL MySQLi PDO
Introduced with PHP version 2.0 5.0 5.1
Development status Maintenance only in 5.x; removed in 7.x Yes Yes
Lifecycle Deprecated in 5.x; Removed in 7.x Active Active
Recommended for new projects No Yes Yes
OOP Interface No Yes Yes
Procedural Interface Yes Yes No
API supports non-blocking, asynchronous queries with mysqlnd No Yes No
Persistent Connections Yes Yes Yes
API supports Charsets Yes Yes Yes
API supports server-side Prepared Statement No Yes Yes
API supports client-side Prepared Statement No No Yes
API supports Stored Procedures No Yes Yes
API supports Multiple Statements No Yes Most
API supports Transactions No Yes Yes
Transaction can be controlled with SQL Yes Yes Yes
Supports all MySQL 5.1+ functionality No Yes Most

Now, let’s discuss some functional differences of above three extensions.

Connection to MySQL database

In MySQL function we can connect to the database by following code:

<?php
    $connection_link = mysql_connect("host.domain.com", "username", "password");
    mysql_select_db("database_name", $connection_link);
    mysql_set_charset('UTF-8', $connection_link);
?>

In MySQLi to create a connection just instantiating a new instance of MySQLi and using a username with a password connecting to the database, as follow:

<?php
     $mysqli_db = new mysqli(‘host.domain.com’, 'username', 'password', 'database_name');
?>

In PDO We need to create a new PDO object. The constructor accepts four parameters for specifying the database source which are DSN (data source name) and optionally username, password. DSN is basically a string of options of driver to use and connection details of database.

<?php
    $pdo = new PDO('mysql:host=host.domain.com;dbname=database_name;charset=utf8','username','password'); 
?>

You can pass fourth parameter as of several driver options as an array. Some PDO drivers do not support native prepared statements, so I recommend pass the parameter which put PDO into exception mode, so PDO performs emulation of the prepare. You can also manually enable this emulation. To use the native server-side prepared statements, you should explicitly set it false. Prepare emulation should be turned off to use PDO safely.

It will throw PDOException object if there is any connection error, we can catch it to handle Exception. So we can set attributes after PDO construction with the setAttribute method:

<?php
    $db = new PDO('mysql:host=localhost.com;dbname=data;charset=utf8', 'user', 'pass');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>

Error Handling

In MySQL

<?php
    $my_result = mysql_query("SELECT * FROM table", $connection_link) or die(mysql_error($connection_link));
?>

We cannot handle the thing in die but die is not a good approach to handle error. Die will end the script abruptly and then echo the error to the screen which you usually don’t want to show to your users, and let hackers to discover your schema.

In MySQLi

mysqli::$error – mysqli_error : Returns a string description of the last error.

<?php
    if (!$mysqli->query("SET a=1")) {
        printf("Errormessage: %s\n", $mysqli->error);
    }
?>

In PDO

In PDO a better solution is exceptions. Anything in PDO should be wrapped in a try-catch block. Also we can force PDO into error mode by setting the error mode attribute from following error modes.

PDO::ERRMODE_SILENT: By setting this error code you must check each result then check $db->errorInfo() to get error details.

PDO::ERRMODE_WARNING: It provides Run-time warnings (E_WARNING) not fatal errors. It’s execution does not halt the script.

PDO::ERRMODE_EXCEPTION: It throw exceptions that shows an error raised by PDO. You should not throw a PDOException with your own code. It acts much like or die(mysql_error()), when it isn’t caught. But we can catch these PDOException and handle as we want.

We can set these error modes as follow:

<?php
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
?>

You can add a try/catch block as like below:

<?php
    try {
        $db->query('hello'); //Invalid query
    }
    catch (PDOException $ex) {
        //$ex->getMessage();
        echo "An Error has occurred";
    }
?>

You can set a user friendly error message instead of exception message. You should use try/catch block for your PDO part also you can use it outside the function that has the PDO functions.

<?php
    function get_data($db) {
        $stmt = $db->query("SELECT * FROM `data_table`");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    try {
        get_data($db);
    } catch(PDOException $ex) {
        echo "An Error has occurred";
        //$ex->getMessage(); // you can log these errors
    }
?>

Fetching Data from database

In MySQL

Using loop on results the username for each row will be the out as following:

<?php
    $my_result = mysql_query('SELECT * from data') or die(mysql_error());
    $num_rows = mysql_num_rows($my_result);
    while($row = mysql_fetch_assoc($my_result)) {
        echo $row['field1'];
    }
?>

In MySQLIi

Using loop on results the username for each row will be the out as following:

<?php
    while($row = $my_result->fetch_assoc()){
        echo $row['username'] . '\n';
    }
?>

In PDO

PDOStatement::fetchAll() – Returns an array containing all of the resultset rows PDOStatement::fetchColumn() – Returns a single column from the next row of a resultset. PDOStatement::fetchObject() – Fetches the next row and returns it as an object. PDOStatement::setFetchMode() – Set the default fetch mode for this statement

query() returns a PDOStatement object by that you can fetch the data directly by using foreach and for loop also.

<?php
    $stmt = $db->query('SELECT * FROM `data_table`');
    $my_results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

Getting the Row Count

Instead of using mysql_num_rows() in MySQL and mysqli_num_rows() or $my_result->num_rows in MySQLi to get the number of returned rows, you can get a PDOStatement and do rowcount, like:

<?php
    $stmt = $db->query('SELECT * FROM `data_table`');
    $row_count = $stmt->rowCount();
    echo $row_count.' rows selected';
?>

Update statements

We use mysql_affected_rows() in MySQL and mysqli_affected_rows() or $my_result->affected_rows in MySQLi.  In PDO, we can do the same by:

<?php
    $affected_rows = $db->exec("UPDATE table SET field='value'");
    echo $affected_rows;
?>

There are some functionalities that are not supported by MySQL and supported by remaining both MySQLi and PDO.

Prepared Statements

A prepared statement is a precompiled SQL statement that can be executed multiple times by sending the data to the server.

The flow of the prepared statement is as follows:

  1. Prepare: The statement template is created by the application and sent to the DBMS. Some parameters are left unspecified by placeholders “?” like as below:
    INSERT INTO data (fname, lname) VALUES (?, ?)
  2. Bind: The DBMS parses, compiles, and performs query optimization on statement template and stores the result without executing it.
  3. Execute: The application binds values for the parameters and the DBMS executes the statement. The application may execute the statement as many times as it wants with different values.

Named placeholders: You can use a descriptive names preceded by a colon, instead of question marks. We don’t care about position or order of value in named placeholder:

$stmt->bindParam(':foo', $foo);

Unnamed placeholders: In unnamed placeholders we must follow the proper order of the elements.

In MySQLi

<?php
    $id = '2';
    $stmt = $db->prepare("SELECT `name` FROM `users` WHERE `id` = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($out_name);
    while($stmt->fetch()){
        echo $out_name . '\n';
    }
?>

In PDO

<?php
    $id = '2';
    $stmt = $db->prepare("SELECT `name` FROM `users` WHERE `id` = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($out_name);
    while($stmt->fetch()){
        echo $out_name . '\n';
    }
?>

API Support

Both PDO and MySQLi provides an object-oriented approach, but MySQLi provides a procedural way also like old mysql extension. New users may prefer MySQLi because of procedural interface which is similar to old mysql extension, So migrating from the old mysql extension is easier. But after mastering in PDO, you can use it with any database you like.

Security

Both PDO and MySQLi provide SQL injection security, as long as developers follow them with features like escaping and parameter binding with prepared statements.

For example a hacker is trying to inject some malicious SQL through the ‘name’ HTTP query parameter (POST):

$_POST['name'] = "'; DELETE FROM users; /*"

If we fail to escape, it will be added in query “as it is”, it will delete all rows from users table as PDO and MySQLi support multiple queries.

In PDO, “manual” escaping

$name = PDO::quote($_POST['name']);
$pdo->query("SELECT * FROM users WHERE name = $name");

In MySQLi, “manual” escaping

$name = mysqli_real_escape_string($_POST['name']);
$mysqli->query("SELECT * FROM users WHERE name = '$name'");

PDO::quote() not only escapes the string, but it also quotes it. But mysqli_real_escape_string() will only escape the string, you will need to apply the quotes manually.

Conclusion

There are only two possibilities to use extension because MySQL is deprecated as of PHP 5.5.0 and removed as of PHP 7.0.0.

  1. MySQLi
  2. PDO

As per my opinion, if there are possibilities to use more than one database drivers or another than MySQL in your project then you can use PDO, otherwise use MySQLi because PDO not support latest functionalities of MySQL.

Laravel 5.4 – OAuth2 Passport Authentation via Mobile Web Services

$
0
0

Laravel support many types of authentications like session, files, tokens with the website, but what about the APIs outside the site or a web service calls from mobile application. Till now we were using the “once:basic” method to authorise the external request from mobile application request of API request.

From Laravel 5.3, it came up with the amazing authentication method called “Passport” to authorise the external request from the internet like accessing the data using API calls as well as the web service calls from the android or IOS mobile applications.

Laravel Passport provides OAuth2 server implementation in a couple of minutes.

I found many developers have only one question which is “Laravel Passport is a very good method to authorise the third party requests, but how do I implement Laravel Passport with the mobile application web-calls/web APIs/web services calls“.

So to get rid out of this, let’s dive into the implementation of Laravel Passport Authentication.

To get started we have to install Laravel Passport into our application, we will do the same via composer.

Open the command prompt in windows and terminal in mac. I assume that your present working directory is the application in which you are going to implement the Passport authentication. Fire below command to install Passport.

composer require laravel/passport

Next, to use the Passport in our application we have to register it as a provider in the array of  “providers” in “config/app.php” file. add below line in an array called “providers“.

Laravel\Passport\PassportServiceProvider::class,

Passport will use it’s own database tables to configure and authorise the requests. So once you get it done with the above things let’s migrate the database with the Passport migrations. Fire below command in your terminal.

php artisan migrate

This will create the tables which are required to store the access tokens of the authorized users. Now let’s fire last command of the passport installation process.

php artisan passport:install

This command will install Laravel Passport service in your application, and will create the encryption keys to generate the secure access tokens for the authorised users.

After firing the above command let’s add the “HasApiTokens” trait to the “app\User” model. By this you can inspect the user’s token and scopes. add below line over the class definition.

use Laravel\Passport\HasApiTokens;

Add below code inside the class definition.

use HasApiTokens, Notifiable;

The whole “App\User” model will look like:

<?php
namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;
}

Now let’s edit the “AuthserviceProvider”. Open “app\Providers\AuthServiceProvider.php” and add below line above the class definition.

use Laravel\Passport\Passport;

Add below line in the boot() method of the AuthServiceProvider class

Passport::routes();

This will register the routes which are required to use Passport authentication.
Finally let’s update the authentication guard in “config/auth.php” let’s update the driver of the api authentication guard to passport instead of tokens.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'tokens',
        'provider' => 'users',
    ],
],

Replace above guards array with the below one in auth.php file

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
     ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Whohaaa! all the configurations have been completed now let’s add api routes and start using the APIs via passport authorisation. As we are registering routes for the APIs, we will add the routes in “api.php” file.

Open routes\api.php file and add below route to access the login api.

Route::group(['namespace' => 'api'], function () {
    Route::get('/login', 'UserController@login');
});

Above route will point the login() method of the UserController class. Let’s create UserController in app\Http\Controllers\api by artisan command:

php artisan make:controller api\UserController

Now open UserController class file and add the login() method code which will authorise the user and send the accessToken in the response after successful authorisation.

The UserController file will look like below.

<?php
    namespace App\Http\Controllers\api;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Auth;
    use App\User;
    use Response;

    class UserController extends Controller
    {
        public function __construct(){
        $this->content = array();
    }
    public function login(){
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
        $user = Auth::user();
        $this->content['token'] =  $user->createToken('Pizza App')->accessToken;
        $status = 200;
    }
    else{
        $this->content['error'] = "Unauthorised";
         $status = 401;
    }
     return response()->json($this->content, $status);    
    }
}

The above code will authorise the valid user and redirect the user to login page if not valid. But as we are using this API from mobile application we are supposed to send the response, instead of redirecting the user login. To do this we have to send “Accept : application/json” along with the header. This will send the response in json format and will not redirect the user to login page.

screenshot-1

As we assume that user has been authorised successfully and received the accessToken, now we will use that access token while requesting other APIs. You have to send the accessToken in Authorization header along with the Bearer keyword, refer below screenshot.

screenshot-2

While this request the below code has been run to return the response of the user details. Now the UserController will look like below:

<?php
    namespace App\Http\Controllers\api;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Auth;
    use App\User;
    use Response;

    class UserController extends Controller
    {
         public function __construct(){
         $this->content = array();
     }
     public function login(){
         if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
         $user = Auth::user();
         $this->content['token'] =  $user->createToken('Pizza App')->accessToken;
         $status = 200;
     }
     else{
         $this->content['error'] = "Unauthorised";
         $status = 401;
     }
     return response()->json($this->content, $status);    
   }

    public function details(){
        return response()->json(['user' => Auth::user()]);
    }
 }

That’s it. you can add other controllers and methods like above.

Cheers!!! :)

App data indexed in spotlight search

$
0
0

With iOS 9, Apple bring many new things for iOS developer. Let’s talk about spotlight search. In iOS 9 new frame work added called “Core Spotlight” which is used to add our app information searchable in spotlight search.

There are 2 way to indexes:

  • A private on-device index
    Each device contains a private index whose information is never shared with Apple or synced between devices. When you make an item available in a user’s on-device index, only that user can view the item in search results.
  • Apple’s server-side index
    The server-side index stores only publicly available data that you’ve marked appropriately on your website.

Now, we are going to see the first way of index by example.

Let’s create new project which display list of restaurants in tableview.

First we create plist file to store information of restaurant [name, description & image].

snap1

After that we will fetch restaurant list from plist file & store in array of restaurant model class.

func loadRestaurants() {
		// we have created Restaurants.plist file in our main bundle
        if let path = Bundle.main.url(forResource: "Restaurants", withExtension:"plist") {
            if let arrObj = NSArray(contentsOf: path) as? [[String:String]] {
                for (_,value) in arrObj.enumerated() {
                    self.restaurantsArr.append(Restaurant(dict: value))
                }
            }
        }
        tblView.reloadData() //reload tableview 
    }

//Model
class Restaurant: NSObject {
    var name : String
    var desc : String
    var imgName : String
    init(dict: Dictionary<String,String>) {
        self.name  = dict["Title"]!
        self.desc  = dict["Description"]!
        self.imgName  = dict["Image"]!
    }
}

Now as iOS developer we know tableview control, so we will display list of restaurants in table

Using below code we are able to display restaurant’s list in tableview.

//MARK:-
UITableViewDelegate,UITableViewDataSource
extension RestaurantListVC:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return restaurantsArr.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 140
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! RestaurantCell
        cell.lblTitle.text = restaurantsArr[indexPath.row].name
        cell.lblDescription.text = restaurantsArr[indexPath.row].desc
        cell.imgV.image = UIImage(named: restaurantsArr[indexPath.row].imgName)

        return cell
    }
}

//Cell class
class RestaurantCell: UITableViewCell {
    @IBOutlet var lblTitle:UILabel!
    @IBOutlet var lblDescription:UILabel!
    @IBOutlet var imgV:UIImageView!
}

snap2

Before we start integration of spotlight search, we must import two frameworks first:

import CoreSpotlight
import MobileCoreServices

Here we have to understand 3 class & use of it:

  • CSSearchableItem
    First we will create searchable item object & configure with attribute set & domainIdentifier.
    DomainIdentifier is used to identify the items group. It’s option argument. We can delete all items of that identifier.
  • CSSearchableItemAttributeSet
    Using attributes we set basic properly like title, description, thumbnailURL & keywords.
    title: Heading title of our item in search result.
    contentDescription: 2 lines of description in search result below the title.
    thumbnailURL: file url which is stored in app
    thumbnailData: you can store server image. First download from url set as Data.
    keywords: Indicate that user searches by keyword. If items match, it will list in spotlight.
  • CSSearchableIndex
    Finally we add our items in array object using indexSearchableItems method of CSSearchableIndex class.

See the code snippet.

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

        for(index,objRes) in restaurantsArr.enumerated() {
            let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
            searchableItemAttributeSet.title = objRes.name
            searchableItemAttributeSet.thumbnailURL = Bundle.main.url(forResource: objRes.imgName, withExtension: ".jpeg")
            searchableItemAttributeSet.contentDescription = objRes.desc
            searchableItemAttributeSet.keywords = [objRes.name,"Restaurant"]

            let searchableItem = CSSearchableItem(uniqueIdentifier: "com.test.spotlight.\(index)", domainIdentifier: "Restaurant", attributeSet: searchableItemAttributeSet)

            searchableItems.append(searchableItem)

        }

        CSSearchableIndex.default().indexSearchableItems(searchableItems) { (error) -> Void in
            if error != nil {
                print(error?.localizedDescription ?? "failed")
            }
        }
    }

let go line by line to make clear.

  • First, Create searchableItem array Object which hold all items to indexed in spotlight search.
  • second, Create searchableItemAttributeSet object & set all basic property.
  • Without keyword there is no result in spotlight. We must set related keyword to item.
  • Then configure the item with identifier & attributeSet append to searchableItems array object.

At last by calling indexSearchableItems it’s indexed to spotlight search. Here we have to pass items array.

snap3

snap4

It’s not finished yet buddy, Still we have one more interesting thing to learn.

How to handle item tap event in spotlight & navigate to specific screen in our app.

In our appDelegate file we have delegate method which received event when user tap on item.

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool

We have implemented this method & handle ahead using NSNotificationCenter and post a custom notification, which handle in the ViewController class.

userActivity object contain userInfo dictionary has identifier value which we set during created CSSearchableItem object in addToSpotlight method.

For more handling code download our project & run it.

snap5

We missed one more thing, after adding at spotlight if we need to update or delete item, How we can do that?

We have to look in CSSearchableIndex class have method for update & delete items. We will look only delete here.

see the below code snippet for delete.

func deleteSearchIndex() {
        CSSearchableIndex.default().deleteAllSearchableItems { (error) in
            if let error = error {
                print("error: \(error.localizedDescription)")
            } else {
                print("Search item successfully removed!")
            }
        }
    }

It will remove all the items from the spotlight index.

Android Things (IOT)

$
0
0

What is Android Things ?

Android Thing is Google’s latest OS, which is Android-based Internet of Things Initiative.
Android Things allow developers to build any smart device using Android APIs and Google Services. Developers can use the Google Weave protocol to communicate between devices along with Google Cloud services like Google Cloud Vision.
Developer can build a smart device using Intel Edison, NXP Pico and the Raspberry Pi 3 as Google has partnered with some of hardware manufacturers.
Android Things explode development of connected embedded devices by providing the same Android development tools, Google APIs and best-in-class Android framework make developers successful on mobile.

android-things1

Application for embedded smart devices bring developers more familiarity with the hardware peripherals and drivers than smartphones and tablets. In addition, embedded devices typically present a single app experience to users.
Android Things extends the core Android development framework with additional APIs which is provided by the Things Support Library.

Let’s explore world of Android Things?

Google already released the developer preview for Android Things OS.Check it here.

Android Things development is more similar with our traditional mobile development because it uses same Android framework and tools. All you need is any of development board which is supported by Things.

android-things2

Let’s setup Development Environment

  1. Download the latest version of Android Studio
  2. Connect your board and verify you can access the device via adb:
    $ adb devices
    List of devices attached
    45675668564791521241    device
  3. Deploy your sample project to your board check your log or message on logcat.

Samples on Android Things can be found here.


Why Should I Choose iOS over Android ?

$
0
0

It is always a big confusion before buying new smartphone, as we have so many options to choose from like iOS, Android, Windows, BlackBerry, Symbian, Bada, Etc.

But in the end final battle will always end up on iOS v Android as both are most adopted mobile operating system around the globe. So let me help choosing right smartphone you deserve.

Here i have listed points where you’ll get your answer “Why Should I Choose iOS over Android ?”

Better Hardware and Software Integration

integration

iOS is not just a platform but it also shows how hardware and software complete each other and best example for this is 3D Touch, a feature that no Android phone could copy.

The 3D Touch display is smart enough to sense pressure, allowing you to take quick actions from the home screen just by long pressing on an app icon and you’ll directly reach exact screen on that app. Hardware on iPhone are capable to perform heavy multitasking even when memory is low.

So if you don’t want your smartphone to hang and have only old fashioned features, iOS is a better choice.

Apps Comes to iOS First

app

There is no doubt that Apple still has the edge when it comes to the number of quality apps available. Most of popular apps are on both platforms but Developers still choose iOS as launch platform of choice for new apps, Prisma and Super Mario Run are recent example for this.

For Instagram it took two years to debut on Android after it launched for iOS and even today we can see that new SnapChat and Spotify features comes to iOS before Android.

Apple curates its store in the sense that developers are obliged to follow stringent rules before getting their app approved for release, means that everything you’ll find on the store has been subject to some degree of quality control.

So if you don’t want to treated like second hand app user, iOS is a better choice.

Uninstall Default Apps

uninstall

User can easily remove default apps in iPhone just like any other downloaded app from App Store in case you find them useless.

On many Android phones, there are a dozen carrier branded apps, and there might be another dozen apps that you will never use but that someone paid the company to install, problem with them is you cannot uninstall these extra apps, only disable them means they still exist on your phone and take up space

So if you don’t want to be slave of your smartphone, iOS is a better choice.

Quick OS Update for Everyone

update-os

iPhone users always get quick and latest iOS update whereas Android updates take months to arrive on device (if you are lucky enough to get one). Most Android smartphones companies do not provide OS update or provide OS update to limited phones but Apple delivers iOS updates to all devices that are three years old.

Speedy updates are more important because security breaches are becoming more serious. As long as Android lags behind in the update world, its devices will be less secure. That’s why millions of Android phones are still running software that’s 3-4 years old

Latest iOS 10 is adopted by 76% of iPhone users but Latest Android OS 7.0 Nougat is adopted in only 2% of all Android devices

So if you don’t want to use old outdated OS in your smartphone, iOS is a better choice.

Security

security

Apple has always had a strong reputation in the security space. This is because, by taking a closed approach to managing its ecosystem, the company retains complete control over what applications and services run on its platform,

Android is open source so anyone can look into system and find ways to crack it. So many malwares are written for Android and Play Store is flooded with Trojanized applications made by criminals. User can also download and install any APK from web (which may or may not available on Play Store), paid Android apps are also available for free download on so many web sites.

So if you don’t want to compromise with security, iOS is a better choice.

Lightning is Far Better than Micro USB

lightning

Apple uses a reversible Lightning cable to charge and sync the iPhone. Lightning is vastly superior to the Micro USB cable that most Android phones use to charge and sync.

With a Lightning cable, there is no wrong way to plug it in because there is not a top or bottom. Lightning cables can charge faster and provide more power than the flimsy and limited micro USB. MicroUSB is limited to 9 watts of power, while Lightning can provide 12 or more. That means more powerful devices, like tablets, can be quickly charged using Lightning.

basically if Apple had chosen Micro-USB, the port would only be able to charge and sync the device, not transmit video signals or do other advanced functions

So if you want to get rid of right side of USB to charge your device, iOS is a better choice.

User Friendly

user-friendly

The iPhone is still easier to pick up and use without issues than most Android phones on the market. There’s no separate app drawer for your apps and no annoying overlay to get in the way.

Android contain confusing widgets and icons layouts which can vary from one phone to the next as firms load their bloatware and launcher style. it takes users longer time to understand how something works on Android then on iPhone.

The main issue is that the majority of Android phones don’t run stock Android. Every Android phone from each manufacturer looks and works differently, because each company puts a different user interface on top

So if you don’t want to get dazed and muddled while using smartphone, iOS is a better choice.

Sharing

sharing

When your friends have iPhones sharing everything is a bit easier using AirDrop and without installing additional apps. User will realise this once a friend switches to Android you’ll quickly find out that you need to download several apps to maintain the same level of sharing that Apple builds in.

There is another feature called “Family Sharing” in iOS. With Family Sharing on the iPhone, mom, dad and the kids can share purchases from the App Store, iTunes and iBooks with up to six people.When Junior wants to make a purchase, you’ll receive an alert via the “Ask to Buy” feature, so you can keep better tabs on what he’s downloading

So if you want more control over sharing, iOS is a better choice.

Privacy

privacy

The Secure Enclave is part of the A7 and newer chips used for Touch ID. The Secure Enclave means, that Apple itself cannot break into an iPhone if it’s a 5s or later and has been protected with a passcode.

“The Secure Enclave uses a secure boot system to ensure that the code it runs can’t be modified,” explains Mike Ash, an expert who has done his best to piece together the principles behind the closely guarded technology, “and uses encrypted memory to ensure that the rest of the system can’t read or tamper with its data. This effectively forms a little computer within the computer that’s difficult to attack”

So if you give highest priority to your data privacy, iOS is a better choice.

Continuity and Handsoff

continuity-handsoff

If you own an iPhone, iPad and Mac your information flows smoothly from one device to the other

with the Continuity feature in macOS, you can use your MacBook to send and receive text messages and even receive and place calls. All you have to do is keep your iPhone nearby

By using Handoff feature user can do things such as start an email on their Mac and then pick up where they left off on their iPhone — or vice versa. Thanks to iCloud keeping everything in sync, you’ll also have easy access to the photos you take on your iPhone from your Mac, as well as any notes or documents you create.

With the latest macOS Sierra, user can use your Apple Watch to unlock your Mac.
Android, You want to say something ?

Don’t be Surprised, it is ionic 3.0

$
0
0

Are you surprised like me while creating ionic 2 project ?

Don’t be Surprised, it is ionic 3. Ionic have updated Ionic 2.0 to Ionic 3.0 to be compatible with Angular 4.0.0 because Angular 4 has been released recently. This upgrade introduces new features like smaller and faster applications, support for a more recent version of TypeScript 2.1 and 2.2.

Ionic 3 will improve the build time and type checking in your application. It also introduces ability to use async await in Ionic Framework, and much more. For more information, see the Angular 4.0.0.

The selectors to style the text color of the native text elements have been removed

h1[color], h2[color], h3[color], h4[color], h5[color], h6[color], a[color]:not([ion-button]):not([ion-item]):not([ion-fab]), 
p[color], span[color], b[color], i[color], strong[color], em[color], small[color], sub[color], sup[color]

These are officially gone and therefore these elements will not get the color unless the ion-text attribute is added.

Creating new application in Ionic 3 is same as ionic 2 but there is some file which is different from ionic 2, some functionality is deprecated and many bugs resolved like alert, content, date-time, infinite-scroll, item-siding, navigation, split-pane, slides and virtual-list.

Ionic 3 has added new Features like module-loader, navigation, split-pane , util, etc.

Create Ionic 3 Application

First of all install the latest version of the CLI and Cordova. And also install recent version of Node.js

Cordova for native app development:

$npm install -g ionic cordova

$ ionic start ionicv3demo --v2

The –v2 flag will still be required for now. This doesn’t mean you’ll get a 2.x.x version of Ionic, just the latest/current (3.x.x) version that has been released

$ cd ionicv3demo

$ ionic serve

What are the updates in ionic 3?

1. For ionic 3 the package.json will consists of the following dependencies

"dependencies": {
    "@angular/common": "4.0.0", 
    "@angular/compiler": "4.0.0",
    "@angular/compiler-cli": "4.0.0",
    "@angular/core": "4.0.0",
    "@angular/forms": "4.0.0",
    "@angular/http": "4.0.0",
    "@angular/platform-browser": "4.0.0",
    "@angular/platform-browser-dynamic": "4.0.0",
    "@ionic-native/core": "3.4.2",
    "@ionic-native/splash-screen": "3.4.2",
    "@ionic-native/status-bar": "3.4.2",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.0.1",
    "ionicons": "3.0.0",
    "rxjs": "5.1.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "^0.8.4"
},
"devDependencies": {
  "@ionic/app-scripts": "1.3.0",
  "typescript": "~2.2.1"
}

2. SplashScreen and StatusBar are updated from using static methods to using injected providers. This is a better code practice.

In app/app.module.ts

import {SplashScreen} from "@ionic-native/splash-screen"; //update in ionic 3
import {StatusBar} from "@ionic-native/status-bar"; //update in ionic 3

providers: [
    StatusBar,
    SplashScreen,
    Storage,
    SharedService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]

and in app/app.component.ts,

import {SplashScreen} from "@ionic-native/splash-screen";
import {StatusBar} from "@ionic-native/status-bar";

this.platform.ready().then(() => {

      StatusBar.styleDefault();
      Splashscreen.hide();

    });

3: BrowserModule and HttpModule
in app/app.module.ts ,

import { BrowserModule } from '@angular/platform-browser'; //update in ionic 3
import { HttpModule } from '@angular/http'; //update in ionic 3

imports: [
BrowserModule, //update in ionic 3
HttpModule, //update in ionic 3
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],

Summary

Creating Ionic v3 is rather straightforward. Ionic 2 to Ionic 3 changes in package.json to support Angular 4, TypeScript 2.2, and Ionic 3. Then, changes from standard StatusBar, SplashScreen to the dependency injected one, and change in BrowserModule and HttpModule.

Create your own animated text using CSS3

$
0
0

Overview

The main criteria of this blog is to discover knowledge about animated texts. This magic is now possible with CSS only.

What is animated text?

The animated text is nothing but a text having some animations on it. Now the question arises in mind is which type of animations we are talking about? The answer is so simple. Here we have used CSS3 animations only which gives some visual effects to our text.

As before we have faced this so many times that in any design we have some animated text or some colorful text. At that time we have just used simple image in a place of text. But nowadays it is very simple to use so,

Let’s have a look on below image and learn how to get a rid of this kind of problems.

blog

CSS3 Properties Used

There are 3 main CSS3 properties used for this and they are as follows:

  1. Background Clip
  2. -webkit-text-fill-color
  3. Animation

Now let’s have look in brief for all properties.

Background Clip:

Background Clip property is used to specify the painting area and it is a new CSS3 property which is not a part of old CSS. Let’s have a look how it works.

HTML

<h2 class=”animated”>This is an Animated Text</h2>

CSS

h2     { font-size: 100px; font-weight: 800; text-align: center; background: linear-gradient(to right, #ffe641 0%, #ffffff 15%, #ffe641 35%, #ffffff 50%, #ffe641 85%, #ffe641 90%, #ffffff 100%) repeat; }

h2.animated { background-clip: text; -webkit-background-clip: text;}

Result
animatedtext-1

When we are writing background-clip: text it specifies the painting area of the text. Please note here -webkit- extension is used to support the CSS3 property in chrome and safari. Currently there is no effect after applying this property. Look at the above screenshot. Now let’s move to the next property.

-webkit-text-fill-color:

-webkit-text-fill-color specifies the fill color of characters of text. By default the text used the default color property if the value of -webkit-text-fill-color is not set. Let’s have at look how it works.

HTML

<h2 class=”animated”>This is an Animated Text</h2>

CSS

h2.animated { -webkit-text-fill-color: transparent;}

Result
animatedtext-2

See the above screenshot. After applying this property we will get this type of transparent text.

Animation

We all know the basic animation functionality. Animations are the part of the design which gives visual effects to our designs. An animation allows an element to change gradually from one style to another. Here we have animated the text background gradually. Let’s have a look on the animations used in our example.

HTML

<h2 class=”animated”>This is an Animated Text</h2>

CSS
@keyframes color-text {
0% {
background-position: 0 0;
}
10%{
background-position: 100px 0;
}
20%{
background-position: 200px 0;
}
30%{
background-position: 300px 0;
}
40%{
background-position: 400px 0;
}
50%{
background-position: 500px 0;
}
50%{
background-position: 650px 0;
}
60%{
background-position: 750px 0;
}
70%{
background-position: 850px 0;
}
80%{
background-position: 950px 0;
}
90%{
background-position: 1100px 0;
}
100% {
background-position: 1262px 0;
}
}

h2 { -webkit-animation: color-text 5s infinite; animation: color-text 5s infinite;}

Result
blog

That’s it!! Hope you enjoyed the blog. Thank you

Which database type Should I follow in my iOS application?

$
0
0

Hummm… In my application I have requirement to deal with database. Which database I should follow? As there are various options available which are as follow:

  1. SQLite
  2. NSUserDefualts
  3. NSCoder
  4. CoreData
  5. Realm

Lets, check each and every option with their pros and cons. So I can decide which option suits for my requirement.

SQLite

Pros

  • You can deal with large number of data.
  • Migration is possible.
  • Simple query just needs to run to fetch data. These queries you have learned in your college time.
  • You can share database file.
  • Cross platform support is possible
  • Browse data is possible
  • Database size is small as compare to Coredata

Cons

  • Slow data fetching process.
  • It’s very complex to add in your project as compare to sqlite.
  • Cannot handle multi threaded situation. If you access two operation on same database table, your database will face deadlock situation.
  • Migration process is very long and complex too. As compare to core data, you have to perform so many steps for migration process.
  • You must have to provide relationships manually.

Comments

Actually, this is a good option but it’s too old. And it is not providing any good feature to handle search and fetch operations like core data and realm is providing. So as per my opinion, if you want to learn how SQLite is working, then you can use this.

NSUserDefaults

Pros

  • Provided by apple.
  • By the way this is not a database, but you can use it as database option to save limited number of data for eg. login token, boolean values, etc.
  • It uses key and value system
  • Very simple to use.
  • You can use this to save small amount of data.

For eg. boolean values.

Cons

  • You cannot use this to store large number data
  • It does not have any type of support to search data by using any query

Comments

Actually this is not a database where you can store large amount of data. So don’t use this if your application scope is big. Because after sometime, you will get stuck as you will find that NSUserDefaults not providing any thing.

NSCoding Protocol

Pros

  • Provided by apple.
  • You can save any view controller with its object without losing any value.
  • You just need to use below two methods to store and fetch data

-(void)encodeWithCoder:(NSCoder*)encoder
-(id)initWithCoder:(NSCoder*)decoder

Cons

  • Its process is slow
  • Again no query method is provided so you have to fetch data manually
  • Store data size is big as compare to NSUserDefault and CoreData

Comments

In last moment, if you have requirement to providing offline support to your application and you don’t have time to go with other option. Then you can use this option. You can store view controller’s data by using NSCoder and then fetch it again to display it. But again for long time support, this option is not preferable.

CoreData

Pros

  • Native framework provided by apple.
  • Very fast processing to fetch data.
  • You can manage large amount of database.
  • Migration process is also simple.
  • Very easy to add in your current source code.
  • Apple provides good feature to handle relationship between two tables. Even SQLite is not have this type of feature.
  • Graph representation is possible.
  • Day by day, apple improving this to make it better. So for long time purpose this is the best option for your application.
  • Multithread is possible but by using different ’NSManagedObjectContext’

Cons

  • Browsing data is much difficult.
  • Database file is not compatible with any other platform like android. So if you are making same application in iOS and android. Then you must have to manage two different database for both platform.
  • Database is not shareable
  • Consuming more memory as compare to SQLite
  • Consuming more space as compared to SQLite

Comments

Definitely you can use this option as your database option. Its fully loaded with necessary features like search, filter etc.

Realm

Pros

  • Very popular in nowadays, this is the first thought in developer’s mind.
  • Easy to Use in your application.
  • By using query you can filter or search any data from database table.
  • Fetching process is faster than core data.
  • Multithread is also possible by using two different objects.
  • Cross platform support is there. So you can use same database for iOS and android version.
  • Share database is possible.
  • You can browse your database too.
  • Migration process is also simple.
  • You can handle large database to.
  • Database size is less as compare to CoreData
  • Less code require to fetch data

Cons

  • It’s not an native framework.
  • More features are not available to handle relationship between two different table. If you are using core data from such a long time, then you can phase this situation only. But for SQLite users will not complain this.
  • Consuming more memory as compare to SQLite
  • Consuming more space as compared to SQLite

Comments

This option is new but good as compare to core data. So you can use this without any issue in your application. Realm also provide good documentation, so you will not phase any kind of problem while implementing it in your application.

Conclusion

From the above pros and cons for all various options, I am suggesting all developers

  1. Only use NSUserDefaults to save only boolean type data. Only consider this for small size of application.
  2. Please don’t use SQLite, instead of you can use Core data or realm. Both options are fully loaded with all type of database functionality.
  3. Now regarding, NSCoder, only use this feature when it is necessary. Don’t make habit to use this. As this option is little bit slow and memory consuming.
  4. Now last, Core Data or realm, see both are good option right now. If you are building application for iOS only then you can use core data. And if your application is for both platform, then you should have to choose realm, because you can use same database file in android or iOS. You don’t have to manage two different database here.

Using CallKit to create a VoIP App

$
0
0

CallKit Framework Overview

CallKit is a new framework and is available in iOS 10 and later. Used to implement VoIP functionality, call blocking, and identification in your app. Apps can use CallKit to receive incoming calls and outgoing calls using the native call UI.

VoIP Push Notification

A VoIP app lets the user make and receive phone calls using an Internet connection instead of the device’s cellular service. Because a VoIP app relies heavily on the network, it’s no surprise that making calls result in high energy use. When not in active use, however, a VoIP app should be completely idle to conserve energy.
For more information about VoIP push notification and PushKit, see Voice over Internet Protocol (VoIP) (https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/OptimizeVoIP.html#//apple_ref/doc/uid/TP40015243-CH30) and PushKit Framework (https://developer.apple.com/reference/pushkit).

Step 1: Prepare To Receive VoIP Push Notification

Now open your application target.Choose capabilities and select ‘Voice over IP’ under background modes

callkit-voip

Step 2: Configure VoIP Push Notification

To configure your app to receive VoIP push notifications, import to the PushKit framework in your app delegate. Create a PKPushRegistry object, set its delegate to self, and register to receive VoIP pushes.

// import to the PushKit framework in App delegate

import PushKit

      // VoIP registration on launch
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.registreVoIP()
        return true
    }

    // Register for VoIP notifications method
    func registreVoIP() {
        let voipRegistry =   PKPushRegistry(queue: DispatchQueue.main)
        voipRegistry.delegate = self
        voipRegistry.desiredPushTypes = [.voIP]
    }

Implement a delegate method to handle updated push credentials. If your app receives both standard push notifications and VoIP pushes, then your app will receive two separate push tokens. Both tokens must be passed to the server to receive notifications.

// Handle updated push credentials
    func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType){
        // Register VoIP push token (a property of PKPushCredentials) with server

    }

 // Handle incoming pushes
    func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType){
        // Process the received push

    }

Step 3: Handle Received Notification

Payload data which you will receive in didReceiveIncomingPushWith method and this method is called even in Background mode.

// Handle incoming pushes
    func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType){
        // Process the received push

        guard type == .voIP else {
            return
        }

        if let strUUID = payload.dictionaryPayload["UUID"] as? String,
            let handle = payload.dictionaryPayload["handle"] as? String,
            let hasVideo = payload.dictionaryPayload["hasVideo"] as? Bool,
            let uuid = UUID(uuidString: strUUID){
            // Handle incoming call

        }

    }

Configure CallKit Framework

Create a “ProviderDelegate” class to handle incoming calls action by extending CXProviderDelegate.

import Foundation
import UIKit
import CallKit

final class ProviderDelegate: NSObject, CXProviderDelegate {

    private let provider: CXProvider
}

Step 1: Configure CallKit capabilities

Configure your call by representing its CallKit capabilities. A CXProviderConfiguration object controls the native call UI for incoming and outgoing calls, including a localized name for the provider, the ringtone to be played for incoming calls, and the icon to be displayed during calls. A provider configuration can also set the maximum number of call groups and a number of calls in a single call group, determine whether to use emails and/or phone numbers as handles and specify whether a video is supported.

// Provider configuration, representing its CallKit capabilities
    static var providerConfiguration: CXProviderConfiguration {
        let providerConfiguration = CXProviderConfiguration(localizedName: NSLocalizedString("APPLICATION_NAME", comment: "Name of application"))

        providerConfiguration.supportsVideo = true

        providerConfiguration.maximumCallsPerCallGroup = 1

        providerConfiguration.supportedHandleTypes = [.phoneNumber]

        if let iconMaskImage = UIImage(named: "IconMask") {
            providerConfiguration.iconTemplateImageData = UIImagePNGRepresentation(iconMaskImage)
        }

        providerConfiguration.ringtoneSound = "Ringtone.caf"

        return providerConfiguration
    }

Step 2: Initialise ProviderDelegate

Initialise CXProvider class with the type and provider configuration which we have just declared.

init() {
        provider = CXProvider(configuration: type(of: self).providerConfiguration)

        super.init()

        provider.setDelegate(self, queue: nil)
    }

Create a method named reportIncomingCall with some basic parameters to update CXCallUpdate by describing the CXHandle type and value like in type you can give options like .phoneNumber, EmailAddress and Generic and a provider will report new Incoming Call to CXProvider.

Using the information provided by the external notification, the app creates a UUID and a CXCallUpdate (https://developer.apple.com/reference/callkit/cxcallupdate) object to uniquely identify the call and the caller and passes them both to the provider using reportNewIncomingCall(with: update: completion:) (https://developer.apple.com/reference/callkit/cxprovider/1930694-reportnewincomingcall) method.

// Use CXProvider to report the incoming call to the system
    func reportIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((NSError?) -> Void)? = nil) {
        // Construct a CXCallUpdate describing the incoming call, including the caller.
        let update = CXCallUpdate()
        update.remoteHandle = CXHandle(type: .phoneNumber, value: handle)
        update.hasVideo = hasVideo

        // Report the incoming call to the system
        provider.reportNewIncomingCall(with: uuid, update: update) { error in
            /*
                Only add incoming call to the app's list of calls if the call was allowed (i.e. there was no error)
                since calls may be "denied" for various legitimate reasons. See CXErrorCodeIncomingCallError.
             */

            completion?(error as? NSError)
        }
    }

Step 3 : Handling CXProviderDelegate

Called when the provider has been reset. Delegates must respond to this callback by cleaning up all internal call state (disconnecting communication channels, releasing network resources, etc.). This callback can be treated as a request to end all calls without the need to respond to any actions.

func providerDidReset(_ provider: CXProvider) {
        print("Provider did reset")

        /*
            End any ongoing calls if the provider resets, and remove them from the app's list of calls since they are no longer valid.
         */
    }

The CXCallAction subclass is an abstract class that represents an action associated with a CXCall Object. The CallKit framework provides several concrete CXCallAction subclasses to represent actions such as answering a call and putting a call on hold. Each instance of CXAction is uniquely identified by a UUID, which is generated on initialization. An action also tracks whether it has been completed or not.

Step 4 : Accept call using CXAnswerCallAction

The Call is connected, the system sends provider(_:perform:) to the provider delegate. In your implementation, the delegate is responsible for configuring an AVAudioSession and calling fulfill() on the action when finished.

func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {

        /*
            Perform your action after accepting the call
        Ex.
            1. Configure the audio session, but do not start to call audio here, since it must be done once the audio session has been activated by the system after having its priority elevated.
            2. Trigger the call to be answered via the underlying network service.
            3. Signal to the system that the action has been successfully performed. 
                action.fulfill()

            4. Signal to the system that the action was unable to be performed. 
                action.fail()

         */
    }

Step 5 : End call using CXEndCallAction

When the user initiates an outgoing call the provider sends provider(_: perform:) to its delegate. The Provider’s delegate calls the fulfill() method to indicate that the action was successfully performed.

func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
       /*
            Perform your action after ending the call
        Ex.
            1. Stop call audio whenever ending the call.
                2. Trigger the call to be ended via the underlying network service.
            3. Signal to the system that the action has been successfully performed.
                  action.fulfill()
            4. Remove the ended call from the app's list of calls.

         */

    }

Step 6 : Hold the call using CXSetHeldCallAction

When a caller places a call on hold, callers are unable to communicate with one another until the holding caller removes the call from hold. Placing a call on hold doesn’t end the call.

When the user or the system places a call on hold the provider sends provider(_: perform:) to its delegate. The Provider’s delegate calls the fulfill() method to indicate that the action was successfully performed.

func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
       /*
            Perform your action holding or unholding the call
        Ex.
            1. Stop or start audio in response to holding the call.
                2. Signal to the system that the action has been successfully performed.
            action.fulfill()
         */

    }

Step 7: Initiate call from AppDelegate

AppDelegate you can call a displayIncomingCall method inside didReceiveIncomingPushWith PKPushRegitryDelegate method to initialise your call.

class AppDelegate: UIResponder, UIApplicationDelegate, PKPushRegistryDelegate {

    var providerDelegate: ProviderDelegate?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool{
        providerDelegate = ProviderDelegate(callManager: callManager)
        return true
    }

    // Handle incoming pushes
       func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) {
        // Process the received push
        guard type == .voIP else { return }

        if let uuidString = payload.dictionaryPayload["UUID"] as? String,
           let handle = payload.dictionaryPayload["handle"] as? String,
           let hasVideo = payload.dictionaryPayload["hasVideo"] as? Bool,
           let uuid = UUID(uuidString: uuidString)
        {
            // Handle incoming call
            displayIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo)
        }
    }

    // Display the incoming call to the user
    func displayIncomingCall(uuid: UUID, handle: String, hasVideo: Bool = false, completion: ((NSError?) -> Void)? = nil) {
        print("uuid \(uuid)")
        providerDelegate?.reportIncomingCall(uuid: uuid, handle: handle, hasVideo: hasVideo, completion: completion)
    }

}

callkit-voip-video

Source Code:

https://developer.apple.com/library/content/samplecode/Speakerbox/SpeakerboxUsingCallKittocreateaVoIPapp.zip

Note

Use of VoIP and CallKit framework in your app you’ll need to give the proper description of the usage of both feature otherwise they may reject your metadata at the time of app Review.

More reference

  1. CallKit Framework ( https://developer.apple.com/reference/callkit )
  2. Enhancing VoIP Apps with CallKit ( https://developer.apple.com/videos/play/wwdc2016/230/ )

Success story of the game Ballz – The No. 1 game in App Store; the biggest hit of the year 2017 by Yudiz Solutions!

$
0
0

Can developing one small game make you a successful entrepreneur?

Everyone likes to play games, don’t you? People have an inborn love of playing games regardless of age, gender or nationality. A mobile game that challenges your skills, a game that needs an eye for angles, a Breakout-style game is what is Ballz which was developed by Yudiz.

Ballz is a Mobile game that took the phenomenal success overnight, and continues to hold out. At present, Ballz is considered to be the No.1 game in the App store having over 5,000,000 downloads. Due to an entire new concept and sober graphics this game has topped the charts and has allowed our clients to get great success. With a right monetization strategy, we have been able to provide good returns though the app is free. Some players tend to spend a lot of money in in-app purchases while some ad integrations generates a good revenue through games. This is how a determined entrepreneur can nail it through developing small but entertaining games.

In Ballz, the idea is to break as many bricks as you can before they move down to the bottom. You have to know your angles, collect all the items to get additional balls, and and try to beat the highest scores and make an endless ball chain! In case, the ball go through white circles, you can earn extra balls, and you can also hit through yellow ball to win rings. Spend coins to unlock more abilities and get an edge on the game.

What the Startups can learn from the success of the game Ballz?

Game Industry is an evolving industry. Innovative new technologies and games are always on the horizon. Games are addictive and pervasive. If we speak in terms of sales, game industry has been beating other entertainment industries like movies and music. More than 80% of the users spent more time in mobile games than apps like social apps or music apps stated in the year 2016.

Ballz is a simple puzzle game but it’s fresh concept makes it engaging and popular among the users. The Ballz game was a startup idea and has gained popularity rapidly due to its unique gameplay and beneficial monetisation methods. Hence we suggest to get into game business to those entrepreneurs who are out there looking to build a successful business but don’t know how to do it. Getting a game developed is your thing as it requires minimum investment and offers a great chances of giving you high profits. If you have a really good game idea and need help in executing the concept, we are here to make it a reality. Contact Us

The idea, monetization techniques, a right strategy and a right development partner is what makes startups more successful. Yudiz has an exceptional record of success and fame in developing mobile games, Augmented Reality and Virtual Reality apps and Games.

Learn Size Classes In Xcode 8

$
0
0

Before few years ago,It was very hard to make UI in both orientations but now with size classes & Xcode 8 it’s very easy to do.

Let’s understand the basic concept

There are two size classes that can be applied to the horizontal (width) or vertical (height) dimension

  1. regular
  2. compact

The iPhone 6 Plus and iPhone 7 Plus are the only iPhone devices with a regular width in landscape orientation as you can see in below image [right side]. The bigger size is always regular and the small size is always compact.

xcode1

The other iPhone models have a trickier set of size classes to remember. The bigger size of the device is regular in portrait mode, but become compact in landscape mode.
xcode2

Let’s open main storyboard, at bottom is toolbar appearing with all devices icon repeat to size class.

xcode3

We will change component position based on orientation.

Portrait Mode

xcode4

Landscape Mode

xcode5

First in portrait mode , Drag image view & label in view controller & set content according.

Now, Let go step by step, Make sure you select portrait mode

    1. Select the vary for traits button in toolbar that will open one dialog pop up. There are two variations height & width.
      xcode6
    2. Select height & width in pop up that will change toolbar in blue color & also change device icon according size class in panel.
      xcode7
    3. Set all constraints for ImageView & Label
    4. Click on done in toolbar panel
      xcode8

Cheers!!!…Here our first step is finished & portrait layout set according size class.

Now we set landscape mode

      1. Click on landscape icon in bottom panel.
      2. Click on vary for traits button & select height, check box will be appear with blue toolbar
        xcode9
      3. Re-arrange imageview & label & set constraints
      4. Click on done button to finish.

Now run project & check it.


Zen Code (Emmet): Quick way to write HTML code [Booster For HTML Coding]

$
0
0

Overview

In day to day life of a html developer, the html tags “< />” works as companion. With these tags the developer creates some awesome layout for webview or other visual stuff, but for all these they have to do lots of line code.

“Zen Code” is the one of the best way to boost these coding practice. Nowadays ”Zen Code” is known as “Emmet” because it was developed by Emmet team.

If you can type one line of code and after that it will convert in your desired html code, doesn’t that sound wow? – Yes, you can do this through zen code. Only thing you require is “Zen Code Plugin or Zen Engine” for your particular text editor that’s it, the special thing about “Zen Code Plugin” is also available for “Notepad++”. Also, it is open source so it is free of cost and available for most of the editor in the market.

Code editor support:

  • Eclipse
  • Netbeans
  • Sublime Text
  • Dreamweaver
  • Editplus
  • EmEditor
  • Notepad++
  • Other famous in market.

Based on editor they provide some shortcut keys to execute zen-code to html format, which you can find from documentation of that plugin.

For Creating HTML 5 Doctype in blank document (file)

In Zen Code:

! or html:5

In HTML:

<!DOCTYPE html>
<html lang="en" >
  <head>
    <meta charset=”UTF-8”>
    <title></title>
  </head>
  <body>
  </body>
</html>

. For define an element class

In Zen Code:

div.header

In HTML:

<div class=”header”></div>

# For define an element id

In Zen Code:

div#logo

In HTML:

<div id=”logo”></div>

+ For define an element siblings

In Zen Code:

div#logo+ul#header-navigation

In HTML:

<div id=”logo”></div>
<ul id=”header-navigation”></ul>

> For define an element child

In Zen Code:

div.header>div#logo+ul#header-navigation

In HTML:

<div class=”header”&gt
  <div id=”logo”></div>
  <ul id=”header-navigation”></ul>
</div>

* For define an element as multiplication

In Zen Code:

div.header>div#logo+ul#header-navigation>li*4

In HTML:

<div class=”header”>
  <div id=”logo”></div>
  <ul id=”header-navigation”>
    <li> </li>
    <li> </li>
    <li> </li>
    <li> </li>
  </ul>
</div>

[ ] For define link for anchor text

In Zen Code:

div.header>div#logo+ul#header-navigation>li*4>a[href=#]

In HTML:

<div class=”header”>
    <div id=”logo”></div>
    <ul id=”header-navigation”>
      <li><a href=”#”></a></li>
      <li><a href=”#”></a></li>
      <li><a href=”#”></a></li>
      <li><a href=”#”></a></li>
    </ul>
</div>

$ For define an element numbering

In Zen Code:

div.header>div#logo+ul#header-navigation>li*4>a[href=#].link$

In HTML:

<div class=”header”>
    <div id=”logo”></div>
    <ul id=”header-navigation”>
      <li><a href=”#” class=”link1”></a></li>
      <li><a href=”#” class=”link2”></a></li>
      <li><a href=”#” class=”link3”></a></li>
      <li><a href=”#” class=”link4”></a></li>
    </ul>
</div>

{ } For define custom text

In Zen Code:

div.header>div#logo+ul#header-navigation>li*4>a[href=#].link${nav item}

In HTML:

<div class=”header”>
    <div id=”logo”></div>
    <ul id=”header-navigation”>
      <li><a href=”#” class=”link1”>nav item</a></li>
      <li><a href=”#” class=”link2”>nav item</a></li>
      <li><a href=”#” class=”link3”>nav item</a></li>
      <li><a href=”#” class=”link4”>nav item</a></li>
    </ul>
</div>

( ) For append two or more zen code

In Zen Code:

(div.header>div#logo)+(div>h1{hi this is heading})

In HTML:

<div class=”header”>
    <div id=”logo”></div>
</div>
<div>
    <h1>hi this is heading </h1>
</div>

So, working smart is better than working like machine that ultimately saves time and efforts. Definitely zen code is one of the best tool in market for making smart HTML in less time and accurate DHTML structure.

Share Extention in iOS App

$
0
0

Share extensions was introduced in iOS 8. Share extension is useful for sharing content like images, videos, text, etc. in your app from any app. Before iOS8, to share the content, it was done by first copying the content and then open an app in which we want to share and then perform share action. But by using share extension in iOS app, there is no need to open an app to share any content.

Implement Share Extension with Steps

CallKit is a new framework and is available in iOS 10 and later. Used to implement VoIP functionality, call blocking, and identification in your app. Apps can use CallKit to receive incoming calls and outgoing calls using the native call UI.

First you need to create an app, in which you share content from other app.
share-extention1

Now create share extension, go to File->New->Target.
share-extention2

Select Share Extension from Application Extension. Provide a name of your Extension.
share-extention3

share-extention4

Now XCode will ask you to active the scheme, Click on Active button.
share-extention5

It will include following list of file in your project folder.
share-extention6

Enable App Groups.

  1. Select project target and go to Capabilities.
  2. Select development team and turn on App Group
  3. Now list of app groups will be shown. Select your app group.
  4. Now select extension from target and do the same to enable app group in share extension.
  5. Now app is configured and ready to share content.

share-extention8

share-extention7

share-extention9

Now build and run your extension by choosing extension from active scheme as following.
It will ask to select an app to run, here we will select Photos and press Run.

  1. It will directly open photos.
  2. Now select any photo from photos and click on share button.
  3. If you don’t get extension name, then click on more and enable extension from list.

share-extention12

share-extention10

share-extention11

share-extention13

Now click on that and get following screen.
share-extention15

Composer sheet is available with content and image. Click on the Post button. But nothing happens. Now if you want to handle delegate method, when user click on post button, respected content will be shared to your application you have to go through the extension classes.

Extension Classes

  1. When Share extension is added by default ShareViewController.swift, and MainInterface.storyboard is created.
  2. By default ShareViewController.swift inherits SLComposeServiceViewController, that have it’s UI for share extension.
  3. If you want your own UI design, then you can inherit UIViewController instead of SLComposeServiceViewController in ShareViewController.swift file.

Following steps describe line of code that you have to write in your share extension class files ShareViewController.swift.
isContentValid: This method is used to validate the content like sharing text length, etc.

override func isContentValid() -> Bool {
        // Do validation of contentText and/or NSExtensionContext attachments here
        return true
}

didSelectPost: This method is called when user press the post button. This is the place where you can do sharing. The method completeRequestReturningItems([], completionHandler:) must be called for uploading task, so host app can do stuff without blocking main thread.

override func didSelectPost() {
        if let item = self.extensionContext?.inputItems[0] as? NSExtensionItem{
            for ele in item.attachments!{
                let itemProvider = ele as! NSItemProvider

                if itemProvider.hasItemConformingToTypeIdentifier("public.jpeg"){
                    NSLog("itemprovider: %@", itemProvider)
                    itemProvider.loadItem(forTypeIdentifier: "public.jpeg", options: nil, completionHandler: { (item, error) in

                        var imgData: Data!
                        if let url = item as? URL{
                            imgData = try! Data(contentsOf: url)
                        }

                        if let img = item as? UIImage{
                            imgData = UIImagePNGRepresentation(img)
                        }

                        let dict: [String : Any] = ["imgData" :  imgData, "name" : self.contentText]
                        let userDefault = UserDefaults.standard
                        userDefault.addSuite(named: "group.yudiz.shareKitDemo")
                        userDefault.set(dict, forKey: "img")
                        userDefault.synchronize()
                    })
                }
            }
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

Make change in info.plist in your share extension for share image.

<key>NSExtension</key>
    <dict>
        <key>NSExtensionAttributes</key>
        <dict>
            <key>NSExtensionActivationRule</key>
            <dict>
                <key>NSExtensionActivationSupportsImageWithMaxCount</key>
                <integer>1</integer>
            </dict>
        </dict>
        <key>NSExtensionMainStoryboard</key>
        <string>MainInterface</string>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.share-services</string>
    </dict>

Setting this property extension is shown when only one image is selected. We can set this property to hide or show extension when more than one image is selected.

Show shared content in your app

Add following code in your ViewController to get shared image and text.

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let userDefault = UserDefaults.standard
        userDefault.addSuite(named: "group.yudiz.shareKitDemo")

        if let dict = userDefault.value(forKey: "img") as? NSDictionary{

            let data = dict.value(forKey: "imgData") as! Data
            let str = dict.value(forKey: "name") as! String

            self.imgView.image = UIImage(data: data)
            self.lblText.text = str

            userDefault.removeObject(forKey: "img")
            userDefault.synchronize()
        }
    }

Check image sharing

Run your project (Select your app as a target not the extension).
First time image and text gets empty.
share-extention16

Now stop app and run your extension, select photos app. Photos app now opened. Select any photo, tap on share button. Select your app extension form activityViewController, if your app is now listed then go to More and switch on your extension to share.
Now tap on your extension, add some text and press on Post button.
share-extention17

Close Photos app and open your app, you will see selected photo and entered text in your app now.
share-extention18

I hope you find this blog very helpful while working on Share Extension.
Thank you.

When to Redesign Your Website

$
0
0

Overview

Redesign website is one of the last things you think about your business. However, it’s important to understand what role your website plays in your customer efforts. For marketing to be every touch point with a prospective customer must include your website which is one of your most important.

Redesigning is Overrated, All design should be a clear goal or a problem to solved first. If your website was made 10 years ago, then looking outdated could be a valid problem. If your conversion rate is at its all time lowest, that is a valid problem too.

They are many reason to redesign your website.

The Current Design is Not Proper Flexible Design.

It’s important that design is to help move forward rather than in the way. Good design speeds up decision making support, it easy to maintain and update. Good design is flexible but a set of rules and limitations.

An Overhead Content in Homepage.

A big mistake is the user with a difficult amount of content right on the homepage of your site. It can be try and fit in as much information as possible with the understandable that if you present it to the user up front, Unfortunately, that is not the case. You have only a few seconds to capture the interest of a website visitor, so you must be concise and to the point with the content you supply on your homepage.

Let your landing pages showcase additional details that a user may find relevant as they move further down the tunnel.

Your Web Site Design Isn’t Proper Responsive.

Responsive design makes a website easily to fit the screen sizes of any mobile device. In reviewing your analytics if you discover that a large amount of your website visitors are a mobile device it’s time for a responsive design. Your website visitors using different mobile devices such as an iPad, iPhone, Tablet, Samsung Note etc. A responsive design makes possible for visitors to navigate your website easily providing a great user experience.

Your Services and Products Has been Changed in your Business.

A major version update, a big and new headline product – all of this might be asking for a new design. It’s also possible that your biggest changes is simply your website at marketing message. For instance, you change the focus of your website or product from B2C ( Business to Client ) to B2B ( Business to Busines ) Model. Simply put, make sure the look up your website send the same message as your product and marketing. Otherwise you can end up with the wrong people for that right product.

Your Website is not user friendly and proper SEO Architecture.

A website redesign can help you improve your site architecture so that it is more SEO ( Search Engine Optimization ) friendly. A website redesign can helps you improve your coding and make your website as a utilizing custom page urls, H1, H2, H3 Tags, Page Titles and Alt Tags by utilize a more advanced CMS ( Content Management System ) that gives you greater flexibility and makes optimizing your website easier.

Currently Your Website does not Support Present Marketing Environment Strategy.

Implementing content marketing as part of your marketing strategy can help you build, establish increase traffic and leads. If you are planning to implement a content and your current website architecture wasn’t built, a website redesign can make it easier for visitors to find your content, a new website will help you to set a better foundation to get you on the right path to successful of content marketing strategy of your websites.

Your Website Security Improvements.

One of the greatest concerns of our time is cyber security, and small businesses, website hacking and viruses as larger businesses. If your website hasn’t been updated from a long time, you are at greater risk for malware and hacking.

Animation Using Lottie in iOS

$
0
0

Animation is a very powerful tool for communication, It make user experience richer than ever and draw attention of user toward specific thing.

But creating animation in app is not easy and fun as it looks. Developer either need to write bulky hard to manage code or add so many images for different screen sizes which makes app big in size. Due to this reason most apps don’t use animations.

Airbnb provides an open source library called Lottie to implement animations in app easily. Lottie Library renders After Effects animations in real time and allow app to use animation easy as using static images. This animations can be paused, looped, resized, sped up and slowed down.

Let me help you implement this.

Step 1 : Setup Project with Pods

First of all we’ll create a “Single View Application”
lottie-img1

lottie-img2

To use Lottie Library we have to install CocoaPods, If you are not familiar with CocoaPods, Please visit this site for detailed information : https://cocoapods.org/
In terminal first move to project directory and then by using

pod init

command project will be initialized with pod
After pod is successfully initialized, we have to update Podfile
Update Podfile as below:

target 'AnimationUsingLottie' do

  use_frameworks!
   pod 'lottie-ios'

end

lottie-img3

After changes save Podfile and install pod by

pod install

command in terminal
Once pods are successfully installed, project will have workspace file and from now onwards we will use workspace file to work with project
lottie-img4

Step 2 : Create JSON File of Animation

As we are rendering Adobe After Effects animations, we must have one animation file created in After Effects (you can get sample files from Lottie sample app)
To create JSON file from After Effects we must enable “Allow Scripts to Write Files and Access Network” from Preference -> General (shortcut : command ⌘ + option ⌥ + ; )
lottie-img5

Now we can easily create JSON file from Windows menu -> Extentions -> Bodymovin
In appeared screen, select composition (animation) and Destination Folder (where you want to export json file) then select Render button and we are Done !!
lottie-img6

Step 3 : Show Simple Animation

Open project workspace file, Add one button on Storyboard and create IBAction named

startPinAnimation

for same. On tap of this button we will display animation.
Our basic setup is ready and we can move to adding animation and for that first we need to

import Lottie

in class file.
Create an object of

LOTAnimationView

class

var animationView = LOTAnimationView()

To initialize animation view object animation file name is required (generated from Adobe After Effects) and file must have .json extention
Create a method to initialize animation view object with frame and animation name then add it in ViewController
We have to call

play()

method of animation view object to start animation

func animatePin() {
     animationView = LOTAnimationView.animationNamed("PinJump")
     animationView.frame.size = CGSize(width: 340, height: 340)
     animationView.center = self.view.center
     self.view.addSubview(animationView)
     animationView.play()
}

Lottie provides two

play()

methods one as we used in above example but we can also use

play()

method with completion block if we want to do something after animation

animationView.play { (success : Bool) in
   // Any stuff to do after animation
}

Call

animatePin()

method from “Show Animation” button action and run app

@IBAction func startPinAnimation(_ sender: UIButton) {
   animatePin()
}

lottie-img7

With only few lines of code we have successfully added animation in our app, but it stops after one iteration to prevent this we can enable looping by using

loopAnimation

property

Step 4 : Enable Looping in Animation

Add another button in storyboard (set hidden property true), on tap of this button we will toggle looping
We have to update

animatePin()

method by passing looping status
I have updated code with above changes and minor other changes like update button title as per looping status, so final code will look like this :
lottie-img8

Finally our code is ready, now run app and enjoy animation.
lottie-img9

We can also do stuff like speed changes using

animationSpeed

property and pause animation using

pause()

method.

Deep Linking in iOS using Firebase

$
0
0

What is Deep Linking?

Deep linking is a way to pass data to your application from any platform like, website or any other application. By tapping once on link, you can pass necessary data to your application.
By using these data application will perform operation.

It might be possible that, sometime when user does not have application on their device then you have to manage this type of situation. You have to open apple store or google play so user have option to download application.

This is the main reason we are using firebase dynamic links, you can manage these link functionality as you want. By clicking once to the link, you can navigate to iOS application or android application.

Get started

Step 1: [Create simple Xcode project]

For this demo, first create a Xcode project by selecting a template for our project Single View Application type.
linking-image1

Step-2 [Create a podfile and add SDK]

Open terminal and navigate to your project directory and run following command:

pod init

Open podfile and include following pod to it

pod 'Firebase/DynamicLinks'

Run pod install and open .xcworkspace file.

Step-3 [Setting up firebase project]

Login with your Google account and go to Firebase Console.
Click on Create Project. Enter your project name and country.
linking-image2

Your Firebase project has been created and you have been redirected to the dashboard. You can integrate a lot of things from this one firebase project into your app.
Select platform as iOS or whatever you want to configure from dashboard.
linking-image3

Enter your app bundle ID and click on Add app button.
Now Go to your firebase project setting and setup App store ID and Team ID
linking-image4

Team ID can be found in membership portal in developer account.
You can copy any app store ID from itunes for testing purpose. Whenever user clicks on dynamic link and if your app not install in his device, User automatically redirect to app store and after installing your app redirect to specific content in your app.
Download ‘GoogleService-Info.plist’ file and add to your project.

Viewing all 595 articles
Browse latest View live