Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

NativeScript - Course Overview

In this course you will learn about:

 Introduction To NativeScript

 Getting started with Nativescript

 User Interface

 Navigation and Routing

 Extending With Plugins

 Events and Binding

 Debugging and Publishing

 Course Summary

What is NativeScript?
 Open Source Framework backed by the company Telerik.

 Create truly native mobile apps for iOS and Android.

o Write once, run anywhere.

o Single code base.

o No DOM.

 Use Angular, TypeScript or JavaScript.

o No Objective C, Swift and Java.

o No cross compiler like Xamarin

 Designed for significant code reuse.

Do I have to use Angular?


Nope! Even though NativeScript has full support for Angular, it has the freedom to choose
the architecture you prefer for your applications.

If you want to use Angular, great! If you want to use just JavaScript, no problem! You can
even build your app in TypeScript or Babel if you want.

NativeScript Vs Hybrid
 Both build apps for multiple mobile platforms from a single source code.

 Hybrid app uses HTML, JS and CSS, while NativeScript uses XML, JS and CSS.

 Can build Android, iOS and windows app through Hybrid development.

 Supported package managers is Bower in Hybrid where it is npm in NativeScript.

Problems with Hybrid Apps


 Performance issues : Hybrid app runs web code inside native webview and it is
having some issues when processing demanding graphics and transitions .
 Limited maintenance for custom plug-ins.
 Behavior and performance are different across platforms.
 Limited number of device apis.

Is it similar to Xamarin and React Native?


All cross-platform applications like NativeScript, React Native and Xamarin, are attempting
to get a solution for the problem statement: The ability to construct great native apps
from a single codebase.

Xamarin is a better suit for engineers who prefer to write code in C#. For developers who
prefer JavaScript, TypeScript or Angular2, NativeScript is the proper choice.

If the app contains complex UI elements, React Native will be the right option. However, if the
developer needs a single code base for cross-platform app, NativeScript can satisfy their
demands.

Why you need NativeScript?


 Free and Open Source

 Native UI: Allows to build truly native apps.

 100% Cross-Platform apps: Write and deploy native apps ( ios and android ) from


a single code base.

 Quick to learn and Skills reuse: Accelerate the learning curve by using existing web
development skills.

 Extensible: Easily reuse existing plugins and NativeScript specific plugins.

Who is using it?


Thousands of developers use NativeScript to build cross-platform mobile applications in
both the iOS App Store and Google Play. Some of the apps are listed below.

 Strudel

 MeWatt

 Herd of Sheffields

 tripist

 LiveShopper etc.

Limitations
 It is a rapidly maturing product that is evolving in realtime. So you need to keep your
codebase up to date to ensure that you are leveraging all the new features that come
with each release.
 Since it needs more time to grow a decent 3rd party community, the number of
components available are limited.
 Still lacking some UI components and options.

Set Up Your System


 Step 1: Install Node.js

 Step 2: Install NativeScript CLI

```sh

npm install -g nativescript

```

 Step 3: Install iOS and Android requirements

 Step 4: Verify the setup and check your installation.

```

tns doctor

```
If you see `No issues were detected`, you are good to go!

Create your First App


 Step 1: Create Your First Project

```sh

tns create HelloWorld

cd HelloWorld

```

 Step 2: Add platforms to your project

```sh

tns platform add android

tns platform add ios

```

 Step 2: Deploy project on device

```sh

tns run android

tns run ios

```

 Step 3: Deploy project in emulator

```sh
tns run android --emulator

tns run ios --emulator

```

What is 'tns'?
In NativeScript you develop and build apps using the NativeScript CLI. After installation, the
NativeScript CLI is available on your terminal or command prompt
as tns (Telerik NativeScript ) or nativescript command.

Choosing an editor
You can develop NativeScript applications in any text editor or IDE you wish. Therefore, if
you’re deeply committed to an editor, by all means continue to use your editor of choice as
you build applications with NativeScript.

Directory Structure
The project folder contains 3 main sub-folders: app, lib and platforms.

 The source code resides in the app folder.

 lib folder contains the Runtime's native C++ implementation and dependencies to


other platform specific libraries.

 platforms folder contains all the specific platform code and libraries for each target
platform that are needed for compiling your app for that specific platform.

Get started with NativeScript Playground


NativeScript Playground provides an ultimate solution to quickly and easily test your
NativeScript code.
This platform allows you to select the language ( TypeScript, AngularJS or JavaScript) in
which you are going to build your application.

We highly recommend you to practice as you learn, for a better understanding of the
concepts.

Using the NativeScript UI


 In NativeScript, the UI is written in XML and coding is done with JavaScript.

 The UI written in XML needs to be broken down to the nodes using XML Parser.

 A node is what is between < and > symbols. To close a <Node>, we use forward slash


(/).

User Interface Components


NativeScript provides a set of UI views (also known as widgets). Most of these views wrap
the corresponding native view for each platform while providing a common API for working
with it.

For example, the Button view renders


an android.widget.Button on Android and UIButton on iOS. Some of the common
components are Button, Label, Image, TextView, SearchBar and Switch etc.

Layouts
It is a special UI element that instructs and informs your app how to organize the UI
elements on a mobile device’s screen. It affect the location and arrangement of UI elements
placed within the layout.
Different types of Layouts
are AbsoluteLayout, GridLayout, FlexboxLayout, DockLayout and WrapLayout.

Types of Layouts
FlexboxLayout is an implementation of the CSS Flexible Box Layout.

AbsoluteLayout sets exact locations (left/top coordinates) for its children.

DockLayout arranges its children at its outer edges and allows its last child to take up the
remaining space.

GridLayout defines a rectangular layout area that consists of columns and rows.

StackLayout arranges its children horizontally or vertically with the orientation property.

WrapLayout positions its children in rows or columns, based on the orientation property,


until the space is filled and then wraps them on a new row or column.

Styling the UI
The NativeScript CSS has some differences from the normal CSS, but overall, it works pretty
similar to how a browser does.

NativeScript supports only three types of selectors viz., ID, Class, and


the Element or Component type in the order of priority.

It does not support modifiers.

Navigation between pages


In NativeScript, Pages are instances of page class of Page module. For navigating between
pages, you can use the methods of the Frame class of the Frame module.

Typically, each app has one frame at the root level - the topmost frame. To navigate between
pages, you can use the navigate method of the topmost frame instance.

The topmost frame


It is the root-level container for your app's UI and you can use it for navigation inside your
app. You can get a reference to this frame by using the topmost() method of the Frame
module.

var frameModule = require("ui/frame");


var topmost = frameModule.topmost();

There are several ways to perform navigation; which one you use depends on the needs of
your app.

Navigate by page name


The easiest way to navigate between pages in NativeScript App is by specifying the file
name of the page to which you want to navigate.

topmost.navigate("details-page");

Navigate using a function


Navigation in NativeScript can also be done in more dymanic way, by providing
a fucntionthat returns the instance of the page to which you want to navigate.

var factoryFunc = function () {

var label = new labelModule.Label();

label.text = "Hello, world!";

var page = new pagesModule.Page();

page.content = label;

return page;

};

topmost.navigate(factoryFunc);
How to pass content between different pages

During Navigation, you can pass context to the page with a NavigationEntry object and it
provides a finer control over navigation. For example, with NavigationEntry you can
also animate the navigation.

var navigationEntry = {

moduleName: "details-page",

context: {info: "something you want to pass to next page"},

animated: false

};

topmost.navigate(navigationEntry);

More options in Navigation


Without History: You can navigate to a page without adding the navigation to the history by
setting backstackVisible to false.

Clear History: You can navigate to a page by clearing the all navigation history by
setting clearHistory to true. This is very useful for multiple-page authentication process.

var navigationEntry = {

moduleName: "main-page",

backstackVisible: false,

clearHistory: true

};
topmost.navigate(navigationEntry);

More options in Navigation


Without History: You can navigate to a page without adding the navigation to the history by
setting backstackVisible to false.

Clear History: You can navigate to a page by clearing the all navigation history by
setting clearHistory to true. This is very useful for multiple-page authentication process.

var navigationEntry = {

moduleName: "main-page",

backstackVisible: false,

clearHistory: true

};

topmost.navigate(navigationEntry);

Angular 2 routing techniques


In NativeScript + Angular-2 application, the navigation is done using the Angular Component
Router.

 Here is the UI

```sh

<Button text="First" [nsRouterLink]="['first']" ></Button>

```

 Here is the Module


```sh

export const routerConfig = [

path: "nested-routers",

component: NestedRoutersComponent,

children: [

{ path: "first", component: SubRouteOneComponent }

];

```

Try it out - Create an App with Navigation


Create an Application with two screens and try to navigate from one page to another using
NativeScript Navigation technique.

Example : First Screen with a list of Books and on clicking of each book directs to detailed
description ( author , language, price, publisher etc. ) of the book.

Available Plugins
There are many NativeScript plugins available and you can find the list of those plugins on
the Telerik Verified Plugins.

Some of the NativeScript plugins are,

 Camera
 Location
 SQLite
 Tooltip
 Accordion etc

Working with Plugin


To install a plugin for your project,

tns plugin add <Plugin>

To use a plugin inside your project, you need to add a require in your app.

var myPlugin = require("myplugin");

To remove a plugin from your project,

tns plugin remove <Plugin>

Location
To include geolocation in your app, use the nativescript-geolocation plugin, accessible
via npm. Here is an example, which shows how to use the specific plugin.

To make the plugin available in your app, run the following command:

tns plugin add nativescript-geolocation

To import the module in your code, use:

var geolocation = require("nativescript-geolocation");

Methods for getting location


 getCurrentLocation: This method gets a single location. It accepts the location
options parameter.
 watchLocation: With this method, location watching does not stop automatically until
the clearWatch method is called.
 distance: This method lets you measure the distance between two locations in
meters.

How to get current location


Here is a simple example for getting current location on tap of a button.

<Page>

<StackLayout>

<Button text="Get Current Location" tap="GetLocationTap"/>

</StackLayout>

</Page>

function GetLocationTap(args) {

var location = geolocation.getCurrentLocation({desiredAccuracy: 3, updateDistance: 10,


maximumAge: 20000, timeout: 20000}).

then(function(loc) {

if (loc) {

console.log("Current location:" + loc);

}, function(e){
console.log("Error:" + e.message);

});

exports.GetLocationTap = GetLocationTap;

Camera
The NativeScript camera plugin was intended for the initial two sections of the job( taking a
photo and optionally saving to device storage).

For Installation,navigate to project folder and run the command

tns plugin add nativescript-camera

Plugin could be added as a standard npm dependency running command

npm install nativescript-camera --save

Requesting permissions
Newer API levels of Android and iOS versions are requiring explicit permissions in order the
application to have access to the camera and to be able to save photos to the device. Once
the user has granted permissions the camera module can be used.

camera.requestPermissions();

Checking Camera Availability


The principal thing that the designers ought to check if the device has an available camera.

The technique isAvaiable will return truer if the camera hardware is ready to use or false if
otherwise.
var isAvailable = camera.isAvailable();

Camera in Simulator / Emulator


camera.isAvailable() method will return false when used in iOS simulator/ Android
Emulator (as the it does not have camera hardware)

Using the camera module to take a picture


Code below shows how to use the camera.

var camera = require("nativescript-camera");

var imageModule = require("ui/image");

camera.takePicture()

.then(function (imageAsset) {

console.log("Result:Img asset instance");

var image = new imageModule.Image();

image.src = imageAsset;

}).catch(function(err) {

console.log("Error:" + err.message);

});

Saving Data In NativeScript App


To save data in your NativeScript Android and iOS application, use different storage
solution that can synchronize with a remote database.

What are some of the best ways to store data locally with a NativeScript app?

Let’s take a look at some options:

 SQLITE

 Google Firebase

 Couchbase

 Local Storage

 File System etc.
SQLITE
NativeScript module providing sqlite actions for Android and iOS.

To install sqlite plugin,

tns plugin add nativescript-sqlite

To use the sqlite module you must first require() it:

var Sqlite = require( "nativescript-sqlite" );

Refer nativescript-sqlite for more details.

Application Lifecycle
NativeScript apps have following life cycle events.

 launch is raised when app launch.


 suspend is raised when the app is suspended.
 resume is raised when the app is resumed after it has been suspended.
 exit is raised when the app is about to exit.
 lowMemory is raised when the memory on the target device is low.
 uncaughtError is raised when an uncaught application error is present.

Event
It is a message sent from an event emitter to signify the occurrence of a specific action.
This event can be generated by a user action or by program logic.

The object that raises the event is called an event sender or event raiser. The object that
consumes the event is called an event listener or event handler.

Adding an Event Handler


Adding an event handler is setting a function that executes when the event is raised.

Below example sets a function that prints a "Tapped!" message in the console, when a button
is tapped.
var testButton = new buttonModule.Button();

testButton.text = "Test";

var onTap = function (eventData) {

console.log("Tapped!");

};

testButton.addEventListener(buttonModule.Button.tapEvent, onTap, this);

Removing an Event Listener


Typically you do not have to remove the event listener. You may need to do it when you need
to receive the event just once or to free up resources.

testButton2.removeEventListener(buttonModule.Button.tapEvent);

Data Binding
It is the process of connecting application UI to the code. Data flow direction is the way
data flows.

NativeScript data binding supports two types of data transmissions.

 One-Wayis the default setting that ensures the target property updates when a change
in the source property occurs.
 Two-Way setting ensures the reflection of changes in both directions —
from targetto source and vice versa.
Binding to an event in XML
There is an option to bind a function to execute on a specific event. This option is available
only through an XML declaration. To implement such a functionality, the source object should
have an event handler function.

Debugging your application


NativeScript uses the built-in Chrome debugging tools to debug your application
on Android and a similar set of tools in Safari for iOS.

You can start the debugging, when you launch your application using the below command.

tns debug android --debug-brk [--device / --emulator / --geny]

The second way is if your application is currently running, you can use the below
command, to connect to an already running application.

tns debug ios --start [ --device / --emulator / --geny]

Publishing your Android application


On Android, you need to build the application using,

tns build android --release --key-store-path=<yourfile> --key-store-password=<your


password> --key-store-alias=<alias> --key-store-alias-password=<password>

This will build you a release version of your APK. The APK's location is going to be
in /platforms/Android/build/outputs/APKs.

You need a key to sign your application so that Google (and others) and you can follow the
instructions at Google Play Store.

Publishing to iOS
On iOS, it is a slightly different process. The first step is to run below command from the
terminal.
tns build ios --release

The main XCode project, the application file is located in the /platforms/ios/ folder that you
will need to open via XCode to submit to the Apple iOS Store.

Then, you can follow the instructions that Apple detail at developer.apple.com.

NativeScript - Course Summary


In this course you have learnt:

 Introduction
 Getting started with Nativescript
 UI and Navigation
 Extending With Plugins
 Events with Data Binding
 Debugging and Publishing

However, NativeScript has a bunch of other components that is not covered in this course. If
you want to get in deep with NativeScript, the better to place to start is Telerik NativeScript
Docs.

Happy NativeScript-ing!

Quiz
1. How to install NativeScript CLI?+A1:B28 NPM INSTALL -G NATIVESCRIPT
2. Can a developer build an app using NativeScript, if he/she doesn't know Java or Objective C/Swift?
YES U CAN DEVLOP a native script
3. tns doctor' command is used to __________. VERIFY THE SET UP AND INSTALLATION
4. NativeScript is backed by __________. TELERIK
5. The source code resides in the ________ folder. APP
6. __________ positions its children in rows or columns, based on the orientation property, until the
space is filled and then wraps them on a new row or column. WRAPLAYOUT
7. In NativeScript, the UI is written in _________ and coding is done with __________. XML,
JAVASCRIPT/
8. How many types of selectors are supported in NativeScript? 3
9. __________ is the root-level container for your app's UI and you can use it for navigation inside your
app. TOPMOST
10. Select one which is not a layout type of NativeScript. WRAPPERLAYOUT
11. To include geolocation in your app, which command has to be executed? TNS PLUGIN ADD
NATIVESCRIPT-GEOLOCATION
12. An event can be generated by __________. BOTH
13. What command has to be executed for adding a standard npm dependency for camera plugin? NPM
INSTALL NATIVESCRIPT-CAM--SAVE
14. camera.isAvailable() method will return false when used in iOS simulator/Android Emulator. T
15. In 'npm install nativescript-camera –save' command, the --save flag will add the plugin as dependency
in your package.json file. T
16. Select the app that developed in NativeScript? ALL
17. Cross compiler is present in NativeScript like Xamarin. F
18. Can developer use platform-specific UI controls with NativeScript approach? YES
19. What is tns? TELERIK NATIVESCRIPT
20. You can navigate to a page without adding the navigation to the history by setting backstackVisible to
true. F(0)
21. NativeScript has cross compiler like Xamarin. F
22. camera.isAvailable() method will return false when used in iOS simulator/Android Emulator. T
(#Spreadsheet::Formula:0x00559ac37052c0)
23. tns debug android --debug-brk [--device / --emulator / --geny]. This command is used for __________.
debugging, when app launch happening
24. main-page.js defines the __________. APPLICATIONLOGIC
25. __________ has the default UI code. MAIN-VIEW.MODEL
26. Lib folder contains the __________ and dependencies to other platform specific libraries.
lib folder contains the Runtime's native C++ implementation
27. How to create your an project in NativeScript? CREATE
28. __________ arranges its children horizontally or vertically with the orientation property. STACK
LAYOUT
29. How to add platforms (android/ios) to your project in NativeScript? tns platform add android, tns
platform add ios
30. __________ file is the entry point to the application. main-page.js
31. JavaScript arrays map to specialized __________ on Android and __________ on iOS. JAVA ARRAY,
NS ARRAY
32. To write business/logic applications, developer wants a local database. Is there any option to have the
same database in all platforms? YES
33. NativeScript can be described as write once, run anywhere. T
34. NativeScript provides single codebase for both android and iOS. T
35. Which of the selector type has highest priority in NativeScript CSS? ID
36. Native Components of TextField are ________ for Android and _________ for iOS.
anroid.weidg.edittext
37. What are all the three selector types supported by NativeScript All

You might also like