Nativescript with angular 2

Post on 16-Apr-2017

946 views 0 download

Transcript of Nativescript with angular 2

Nativescriptfor Angular2

Chris NoringGoogle Developer Expert

Front end Developer at OVO Energy

About me

chris_noring

What’s out there for building apps?

App store and market place = plan for monetizing+ It also has

Built in features like camera, gps, push notifications

+ Has access toNative

swift, objective-c

java

- Usually needsone dev team per platform $$$

Web apps

One team, only needs to know javascript + css+ Cost less

- Limited access to hardware

- Browser support, increase maintenance and dev time

- Monetizing?

Will cost time and money to make it work well on all browsers also continuous work because browsers get updated and breaks stuff

- Doesn’t feel like native, its a compromise

+ Great for simple scenarios like a responsive version of the homepage

geoposition

Hybrid frameworks

- You need to learn its api

rendering in web views, not truly native UI

+ It is possible to use an App Store

- Limited access to hardwarebut the support is getting better and better

WebRTC*WebGL

WebAudioIndexedDB

Web Components*Utilize Hardware Acceleration

Remote Debugging*

- More and more cool features are being supported

A hybrid app is just a regular mobile optimized website, written in CSS, HTML and JavaScript, that is displayed in a webview

IonicCordova

Phonegap

Titanium React Native

Progressive web apps

+ Caches

Is this the future?

- Monetizing?

+ Feels like an app

- Not great support on Safari yet

+ Progressive enhancementbetter features with better browser and better broadband

+ Push notifications

So how does nativescript fit in?

It’s NOT web although javascript, so no DOM

It targets actual apis

Its supports hardware due to being actual native

BUT you can use your javascript and css skills

AND you can use your native developers because

THEY KNOW THE API

It’s NOT either javascript or native folks, ITS BOTH

Nativescript

killer featuresYou can style native ui with css

You can use javascript OR angular 2 with typescript

Is a free and open source framework for building native iOS and Android apps using JavaScript and CSS

You can access native apis with javascript

it’s free

It has hardware accelerated animationsYou can monetise cause you can use App Store and marketsIt’s pluggable, you can use and write your own plugins

How does it work?

Nativescript runtime usesJavascript virtual machines

executed by V8.is JIT compiled and

v8 JavaScriptCore

Android iOS

how does v8 know what android.text.format.Time() is?

var time = new android.text.format.Time();this is javascript

NativeScript uses it to inject APIs that let you access native code.

nativescript inject android/ios object to v8 or Javascript Core

There are APIs on v8 that lets you affect the global scope

How to know what to inject?

JavaScriptCore has a similar mechanism that makes the same technique possible for iOS.

How to interpret the js code?

1) NativeScript uses reflection to build the list of the APIs that are available on the platform they run on.

invokes a callback that native script can intercept, in that interception c++ code is being run

2) android.text.format.Time()

javascript code

corresponding c++ callback

invokes JNI-bridge to talk to native API

Androidinvokes native API

directly

iOS

In conclusionNativescript investigates what to inject and injects metadata based on runtime findings for android/ios

A callback is connected to each executed javascript that nativescript intercepts and runs c++ in its place

C++ code on Android targets JNI ( c++ becomes java ) that targets native API

C++ on iOS talks to native API directly

And presto

Nativescript consists of modules

Modules

camera.android.jscamera.ios.jscamera-common.js

selects the correct one at runtime

require(‘camera’)camera

node_modules/ tns-core-modulesmodulemodulecamera …

usage

everything is made up of modules

How easy is it to get started?

Preparing your environment

npm install nativescript -g

Windows@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://www.nativescript.org/setup/win'))"

Macruby -e "$(curl -fsSL https://www.nativescript.org/setup/mac)"

tns doctorverify your installation

Continued..For android install genymotion

https://www.genymotion.com/

set path to android SDK

First appscaffold

ortns create my-app-name --ng

creates angular2 app

git clone https://github.com/NativeScript/sample-Groceries.gitangular 2 app for nativescript

Scaffolding saves a lot of time

What is the dev experience like?

We got a plugin for vs code so we can set break points

We can use hot reload, so code is recompiled and redeployed on change

We can write and run unit tests

Hot reload

tns livesync platform —watch

1) compiles app 2) deploys to emulator/ devicerepeats 1) + 2) on changes

Debugtns debug platform

starts platform specific debugger with option —debug-brk

—debug-brk—start —stop —emulator

set breakpointperform action

Build and start the applicationStart Node Inspector Launch Chrome browser

tns debug platform

Remote chromium debugger for Eclipse

https://www.nativescript.org/nativescript-for-visual-studio-codePlugin for vs code

ext install nativescript

How hard is it to accomplish something?

So we can be productive with all these components

we code in angular 2

we can easily extend with plugins

we can write our own plugins

we got,

ui components, we got layouts, http, css animations, gestures, hardware and more..

Controls with ng2<Label class="lbl" [text]="title"></Label>

<Button (tap)="click()" text="Save new hero"></Button>

<TextField [(ngModel)]="status"></TextField>

<ListView [items]="todos" (itemTap)="tapped($event)" > <template let-item="item" let-odd="odd" let-even="even"> <StackLayout [class.odd]="odd" [class.even]="even" > <Label [class.done]="item.done" text=“{{item.name}}"> </Label> </StackLayout> </template></ListView>

one-way binding

event binding

two-way binding

So angular 2 with some new components

File system

Whats possible?Create, Read, Update, Delete on files and folders

import * as fs from "file-system";var documents = fs.knownFolders.documents();

var myFile = documents.getFile("Test_Write.txt");

myFile.writeText("Something").then(function () { }, err {});

myFile.readText().then(function (content) {

}, err {});

do something with retrieved content

File demo

Layout

AbsoluteLayout

DockLayout

GridLayout

StackLayout

WrapLayout

Components ends up exactly where you want them

x,y

Arranges children to outer edges, last child takes up remaining space

columns and rows

Horizontally or vertically

follows orientation til space is filled then wraps them into new column/row

Navigation

NavigationNavigation is angular 2 routerif you know how that works

then you know how to build the app

CSS

CSSApplication-wide css, app.css

Component-specific css@Component({ styleUrls : [‘pages/examples/list-demo.component.css']})

@Component({ style : ‘’})

https://docs.nativescript.org/angular/ui/styling.html

Inline css<Button text="inline style" style="background-color: green;"></Button><Button backgroundColor=“lightgray" >

Plugins

What is a native script plugin?

pluginfile.android.tsfile.ios.tspackage.json

lookup iOS and java implementation of the same thing [NSDate date] new Date()).toString()

and add to respective file.platform.tswrite js-ified code corresponding to native api

NsDate.date() (new java.util.Date()).toString()

Is an npm package, published or not, that exposes a native API

http://developer.telerik.com/featured/creating-nativescript-plugins-in-typescript/

Great article to get started

http://plugins.telerik.com/nativescriptTelerik verified marketplace

https://docs.nativescript.org/plugins/pluginsMore details

tns plugin add <Plugin>tns plugin remove <Plugin>

Add/Remove

https://www.thepolyglotdeveloper.com/2016/07/create-native-ios-and-android-plugins-with-nativescript/

Hardware

Cameraimport * as cameraModule from 'camera';cameraModule.takePicture({ width: 300, height: 300, keepAspectRatio: true }).then((picture) => { console.log('picture taken'); this.source = picture; })

<Image [src]="source" stretch="none" horizontalAlignment="center" ></Image>

take picture

import a reference

Display image in control

Camera demo

A word about images

file system<Image src="~/images/logo.png" stretch ="none" />

relative to the app folder

url<Image src="https://www.google.com/images/errors/logo_sm_2.png" />

resource

<Image src="res://logo" stretch ="none" /> App_Resources

AndroidiOS

Should be placed in resp platform

Geoposition

tns plugin add nativescript-geolocationInstall the plugin

Check if its enabled, then ask for permission

import * as geolocation from "nativescript-geolocation";

if (!geolocation.isEnabled()) { geolocation.enableLocationRequest();}

So much for enabling, how to use?

geolocation.getCurrentLocation({ desiredAccuracy: 3, updateDistance: 10, maximumAge: 20000, timeout: 20000}) .then(function(loc) { if (loc) { alert("Current location is: " + loc); console.log("Current location is: " + loc); } }, function(e){ console.log("Error: " + e.message); });

get location, returns a promise

And just use a plugin to show the locationtns plugin add nativescript-google-sdk

Use an actual device to test this one

Once enabled, ask for location

Animation

ctrl.animate({ opacity: 0, backgroundColor: new Color("Blue"), translate: { x: 200, y: 0 }, scale: { x: 2, y: 2 }, rotate: 180, duration: 800, delay: 20, iterations: 1, curve: enums.AnimationCurve.easeIn }) .then(() => { console.log('animation done'); this.ypos += 20; })

We can Rotate, scale, change opacity ..What can we do?

translate

rotate

repeat animation

when done

Animation demo

Nativescript let’s you code an actual native app using the API you know

using javascript

Just remember this..

Thank you for listening