How to Get Started with Kinvey and NativeScript—Fast

How to Get Started with Kinvey and NativeScript—Fast

Posted on January 15, 2019 0 Comments
How to Get Started With Kinvey and NativeScript—Fast_870x450

In this blog, we look at how to get up and running with NativeScript and Kinvey as fast as possible.

NativeScript allows you to build native iOS and Android apps from a single codebase, and Progress Kinvey makes it easy to add the backend plumbing that makes your app work. Together, the two technologies let you build modern mobile apps fast.

In this blog, we’ll take an opinionated look at how to get up and running with NativeScript and Kinvey as fast as possible. If you follow along through the whole article, you’ll set up a new Kinvey account, configure a NativeScript development environment and start to take advantage of some of the powerful backend features Kinvey offers. At the end, you’ll have an app that looks like this:

Final App

Let’s get started.

If you'd like to get an overview of the Kinvey platform, join us for the upcoming Getting Started with Kinvey webinar. Register here.

Step 1: Set Up Your Kinvey Account

First things first, to use Kinvey, you first need to create a free Kinvey account. To do so, head to console.kinvey.com/signup and provide your information to register.

Kinvey Console Signup

After you have an account, Kinvey will prompt you to create a new app. You can name your app whatever you’d like, but if you’d like to follow along with this article, create a new app named Tasks. (You can create additional apps at any time.)

Create App

After you create your app, Kinvey will next ask which client platform you’d like to use.

You can use Kinvey on many different platforms (and switch between those platforms at any time), but for this article we’ll stick with NativeScript, so go ahead and select the NativeScript platform and click Continue.

Select Platform

TIP: Check out the Kinvey documentation to learn about using Kinvey in other environments, such as in your web apps.

Finally, on the next screen, copy your app key and app secret, and paste them somewhere convenient. (If you do lose these keys, I’ll show you where to find them again later in this article.)

App Keys

And with that, you now have your Kinvey account set up and a new app ready to go. We’ll return to Kinvey later to start to leverage its features, but for now, let’s shift over to getting your NativeScript environment ready.

Step 2: Set Up Your NativeScript Environment

NativeScript is a framework for building iOS and Android apps using JavaScript, and, as such, to start using NativeScript you must set up an environment to write your code.

There are a few different ways to do this, but the easiest—and the one we’ll use for this article—is NativeScript Playground. NativeScript Playground is a browser-based environment for developing NativeScript apps without installing any local dependencies. All you need is an iOS or Android device.

Go ahead and visit Playground in your browser of choice. You should see a screen that looks like this.

NativeScript Playground

NOTE: If you plan to submit apps to the iOS App Store or Google Play, you’ll eventually need to set up a local NativeScript environment using either the NativeScript CLI or NativeScript Sidekick. But Playground has everything you need to get started, and we highly recommend using it when you’re first learning NativeScript and Kinvey.

To start developing in Playground, you need to download and install two apps on an iOS or Android device—NativeScript Playground and NativeScript Preview.

You can find the apps by searching for “NativeScript Playground” and “NativeScript Preview” in the iOS App Store or Google Play, or by using the links below.

Once you have those two apps installed on your device and are ready to go, open the NativeScript Playground app on your device and tap the Scan QR code button.

Scan QR Code

Next, in your browser, find and click the QR code button (shown in the screenshot below). This brings up a QR code that you can scan using the Playground app on your device.

Scan QR Browser

After you scan the QR code, you should see the following UI on your iOS or Android device.

iOS NativeScript Playground Android NativeScript Playground

TIP: You can connect multiple devices to a NativeScript Playground app and develop on them simultaneously. To do so, just install the NativeScript Playground and NativeScript Preview apps on multiple devices and scan the QR code on all of them.

And with that, you’re ready to start developing NativeScript apps!

If you’d like, you can experiment by changing the default app’s code in the Playground environment. As soon as you save changes, your device will refresh and you’ll be able to see your updates in action right away.

Now that you have a Kinvey account set up and a NativeScript environment ready, let’s look at how to connect the two technologies.

Step 3: Connect Your NativeScript App to Your Kinvey Account

The easiest way to connect NativeScript apps to Kinvey functionality is through the Kinvey SDK for NativeScript, which provides a series of easy-to-use JavaScript APIs. NativeScript Playground includes the Kinvey SDK in every app you build, so you can immediately start using the SDK APIs with no additional setup necessary.

The first API you need to use is Kinvey.init(), which is the method that makes the connection from your NativeScript frontend to your Kinvey backend. Remember the code snippet you copied during the Kinvey sign-up process earlier? That code is a call to Kinvey.init() with the values you need to make the connection. It looked like this but it included your appKey and appSecret values:

Kinvey.init({
   ...
});


As a next step, you could take this code and paste it into your current Playground app and be on your way, as all Playground apps support the Kinvey SDK out of the box.

That being said, personally I like starting from a more complete app template that has a bit of scaffolding to make my life easier. My personal favorite starting point for NativeScript and Kinvey apps is the “Good-Looking Login Form” example from the NativeScript Marketplace’s code sample listing.

Login Form iOS-2

It’s a simple app, but it has a pre-built, Kinvey-based login form, as well as some of the basic setup necessary to build multi-page NativeScript apps.

Therefore, to follow along with this article, go ahead open the login form sample in your browser, and scan that app’s QR code on your device.

NOTE: The version of the sample we’ll be using is Angular-based, but if you’re a Vue.js fan, you can use this Vue.js-based version of the same login sample.

Next, open the sample’s shared/backend.service.ts file, find the kinveyAppKey and kinveyAppSecret properties, and replace those properties’ values with the values you copied from your Kinvey backend earlier. If you lost those keys, you can find them using the three dots next to your app’s name in the Kinvey console.

Keys

With those values in place, you have now made the connection between your NativeScript front end and your Kinvey backend. Now that you’re done with the setup, let’s look at how to start using Kinvey to do some awesome stuff.

TIP: If you have the NativeScript CLI or NativeScript Sidekick set up, there are additional Kinvey-based templates you can start new apps from. To see them, head to the NativeScript Marketplace’s template listing and search for “Kinvey”.

Step 4: Configure Your Auth

Authorization and user management are often some of the more fun requirements of your average app, but Kinvey makes them easy. In fact, the sample app you’re using already has a fully functional user management system.

To test it, open your app on your device, tap "Sign Up," and register a new user. After you do, you should see a screen that looks like this.

Registration Success

To confirm the registration worked, head to the Kinvey Console, and click the Users option in the navigation. Here, you should see the new user you just registered.

Console Users

There are a few things you can do to customize how user management for your apps works. To see a few of them, head to the user settings in Console using the button shown in the screenshot below.

User Settings

On the Email Verification portion of the settings, you can control whether users need to verify their email addresses before logging in and customize the emails Kinvey will send out on your behalf.

Email Verification

On the Password Reset portion of the settings you can similarly configure your password reset processes, or just let Kinvey take care of everything for you.

Password Reset

While all of this is functionality is powerful, perhaps Kinvey’s most powerful feature is its Mobile Identity Connect, which allows you to connect to a wide variety of existing authentication providers, such as LDAP, Active Directory, Facebook, or really, any provider that supports common protocols like SAML, OpenID or OAuth.

A full in-depth discussion of Mobile Identity Connect is out of the scope of this article, but if you’re interested, check out Kinvey’s documentation on setting up MIC or this tutorial by Brian Rinaldi. When you’re done, you’ll be able to leverage your existing auth provider directly in your apps. For example, here’s what the workflow looks like with an Active Directory setup.

Mic Sample

NOTE: You can view the source of the above application on GitHub if you’re looking for a high-quality NativeScript and Kinvey sample to reference.

Regardless of how you choose to implement authentication for your apps, Kinvey has you covered. When you’re all set, let’s move on to look at how you can start to leverage data from Kinvey.

TIP: For a more in-depth look at how users work in Kinvey, check out Understanding Users in Kinvey by Brian Rinaldi.

Step 5: Configure Your Data

Now that you have Kinvey and NativeScript set up, and you have your user management in place, let’s look at how to work with data.

In Kinvey the building blocks for working with data are called Collections, and you can find yours in the Kinvey Console by tapping on the Collections link shown in the screenshot below.

Collections Menu

To start working with data you need to create collections, so let’s do just that by clicking the Add a Collection button.

Collection Add Button

Give your collection a name (use “Tasks” if you want to follow along with this article), and then tap Save.

Collection Name

On the next screen you’ll see a UI allows you to select between Kinvey’s built-in cloud-based data store, and Kinvey’s data connectors, which allow you to connect to data you already have.

Kinvey data connectors are known as RapidData, and they’re worth checking out if you have existing data in SharePointSQL ServerSalesforceSAP or if you have existing REST APIs. For the purposes of this article, we’ll keep things simple and use Kinvey’s built-in data for the new “Tasks” collection you just started.

As one last step before we use this collection, let’s configure its permissions. Kinvey offers a robust set of role-based permissions that determine which users are able to access collections, and also what actions they’re allowed to take on that data. To enter this configuration for your new collection, find and click the gear icon in the Kinvey Console UI (see screenshot below).

Permissions-1

On the following screen, first click the permissions menu option, and then the pencil that allows you to change your collection’s default permissions.

Permissions 2

On this screen, you can view and change your new collection’s permissions for creating, reading, updating and deleting. Find the read dropdown, change its value from Grant to Entity, and then click the Update Role Access button. This makes it so that users can only read tasks that they created, and not other users tasks.

Permissions-3

TIP: You can read a detailed write up on exactly how access control works in Kinvey in the Kinvey docs.

And with that, your collection is now setup and ready to go. In the next step, let’s look at how you can use your new collection in your app.

Step 6: Use Your Data

Like with authentication, using Kinvey data in NativeScript apps is as easy as making a few simple calls to the Kinvey SDK. To see this, head back to your app in NativeScript Playground.

There are a few changes you need to make to use your new collection. Start by creating a new tasks.service.ts file in your app’s shared folder. In Playground, you can do this by giving focus, to the shared folder, clicking the + button in the explorer, and selecting Add File and then TypeScript.

Create New File

Paste the following code into your new tasks.service.ts file, which creates a simple service for interacting with your Tasks collection using the Kinvey SDK.

import { Injectable } from "@angular/core";
import { Kinvey } from "kinvey-nativescript-sdk";

@Injectable()
export class TasksService {
    private dataStore;

    constructor() {
        this.dataStore = Kinvey.DataStore.collection("Tasks");
    }

    get() {
        const query = new Kinvey.Query();
        // Sort by descending “entity created time” to put new items on top.
        query.descending("_kmd.ect");
        return this.dataStore.find(query);
    }

    save(task) {
        return this.dataStore.save(task);
    }

    handleErrors(error: Kinvey.BaseError) {
        console.error(error.message);
        return Promise.reject(error.message);
    }
}


It’s worth taking a moment to appreciate just how simple the Kinvey SDK makes it to interact with your data. Retrieving data is as easy as calling find() and updating data is as easy as calling save(). (Check out your app’s user.service.ts file if you want to see how simple Kinvey makes it to handling the authentication features we looked at in this article’s previous step.)

Next, open your app’s app.module.ts file and add your new TasksService as a provider. The full code should look like this.

import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { NativeScriptHttpClientModule } from "nativescript-angular/http-client";
import { NativeScriptFormsModule } from "nativescript-angular/forms";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { LoginComponent } from "./login/login.component";

import { UserService } from "./shared/user.service";
import { TasksService } from "./shared/tasks.service";

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        NativeScriptFormsModule,
        NativeScriptHttpClientModule,
        AppRoutingModule
    ],
    declarations: [
        AppComponent,
        LoginComponent
    ],
    providers: [
        UserService,
        TasksService
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

TIP: Need help learning the Angular syntax in this code? Check out our NativeScript Angular tutorial in NativeScript Playground.

Now that you have a service for working with your Kinvey Collection ready to go, you have to alter your app to use it. To do so, open your home.component.ts file and replace its contents with the following code. 

import { Component, OnInit } from "@angular/core";
import { RouterExtensions } from "nativescript-angular/router";
import { alert } from "tns-core-modules/ui/dialogs";

import { TasksService } from "../shared/tasks.service";
import { UserService } from "../shared/user.service";

declare var UITableViewCellSelectionStyle: any;

@Component({
    selector: "app-home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    tasks = [];
    textFieldValue = "";

    constructor(private userService: UserService, private tasksService: TasksService, private routerExtensions: RouterExtensions) {
    }

    ngOnInit(): void {
        this.tasksService.get().subscribe((data) => {
            this.tasks = data;
        }, () => {
            alert({
                title: "Tasks",
                message: "An error occurred retrieving your data"
            });
        });
    }

    onItemLoading(args) {
        if (args && args.ios) {
            // Prevent default iOS behavior of highlighting a tapped item in a UITableView
            // See https://stackoverflow.com/questions/46299915/remove-listview-item-highlight-on-tap-nativescript-angular-ios
            args.ios.selectionStyle = UITableViewCellSelectionStyle.None;
        }
    }

    onTaskCircleTap(task) {
        const index = this.tasks.indexOf(task);
        this.tasks[index].completed = !this.tasks[index].completed;
        this.tasksService.save(task);
    }

    onReturnPress() {
        if (this.textFieldValue.trim() !== "") {
            this.onButtonTap();
        }
    }

    onButtonTap() {
        if (this.textFieldValue.trim() === "") {
            alert({
                title: "Tasks",
                message: "Please input a task.",
                okButtonText: "OK"
            });
            return;
        }

        var task = {
            name: this.textFieldValue,
            completed: false
        };

        this.tasksService.save(task).then((newTask) => {
            this.tasks.unshift(newTask);
        })
        this.textFieldValue = "";
    }

    logout() {
        this.userService.logout();
        this.routerExtensions.navigate(["/login"], { clearHistory: true });
    }
}

There’s a bit of code here that requires some background in NativeScript to understand. If you’re new to NativeScript and having trouble following along with some of the syntax, it might be worth taking a minute to go through the NativeScript getting started tutorial on NativeScript Playground.

The code that interacts with your new service is pretty straightforward though. To see them, make note of the call to tasksService.get() when your component loads, and the call to tasksService.save() when it chooses to add a new task.

To define the UI for this app, open your home.component.html file, and replace its contents with the following markup, which builds a list UI for working with your tasks collection. 

<ActionBar title="" flat="true">
    <ActionItem text="Logout" (tap)="logout()" ios.position="right">
        <Label text="Logout" color="white"></Label>
    </ActionItem>
</ActionBar>

<GridLayout rows="auto, auto, *">
    <Label row="0" class="header" text="My Tasks"></Label>

    <GridLayout row="1" class="input-bar" rows="auto" columns="auto, *">
        <Button id="add-task-button" class="list-entry-icon" col="0" text="+"
            (tap)="onButtonTap()"></Button>
        <TextField col="1" [(ngModel)]="textFieldValue" hint="Type new task..."
            editable="true" returnKeyType="done" (returnPress)="onReturnPress()"></TextField>
    </GridLayout>

    <ListView row="2" [items]="tasks" (itemLoading)="onItemLoading($event)">
        <ng-template let-item="item">
            <GridLayout columns="auto, *" class="list-entry" [class.completed]="item.completed">
                <Label col="0" (tap)="onTaskCircleTap(item)" class="list-entry-icon"
                    text=""></Label>
                <Label col="1" class="list-entry-text" [text]="item.name"></Label>
            </GridLayout>
        </ng-template>
    </ListView>
</GridLayout>
And finally, so that this app looks polished, paste the following code into your home.component.css file, which styles the UI controls you just added.

 

ActionBar {
    background-color: #35495E;
}
ActionItem {
    color: white;
}

.header {
    background-color: #35495E;
    color: white;
    font-size: 34;
    font-weight: 600;
    padding: 0 15 15 15;
    margin: 0;
}

.input-bar {
    border-width: 0 0 1 0;
    border-color: #E0E0E0;
}
TextField {
    font-size: 16;
    color: black;
    placeholder-color: #C1C1C1;
    padding-left: 0;
}
#add-task-button {
    margin: 15 10 15 15;
    padding-bottom: 3;
}

.list-entry {
    padding: 15;
}
.list-entry-icon {
    width: 30;
    height: 30;
    color: #42B883;
    font-size: 25;
    border-color: #42B883;
    border-width: 2;
    border-radius: 50;
    margin-right: 10;
}
.completed .list-entry-icon {
    background-color: #42B883;
}
.list-entry-text {
    font-size: 17;
    vertical-align: middle;
    color: #35495E;
}
.completed .list-entry-text {
    text-decoration: line-through;
    color: #D3D3D3;
}


Save all these changes, and you should now see the following UI on your device for managing tasks.

Tasks in Action

And what’s cool is that if you look at your Kinvey backend, you’ll see that all your changes are saved there as well—even if you used Kinvey’s RapidData to connect to an existing data store like Salesforce or SQL Server.

Kinvey Backend

Cool, huh? Starting with a simple to-do list app like this is a great way to learn what Kinvey and NativeScript can do. With that in mind, here are a few features you could try adding to this sample as a learning exercise.

If you got lost at all during this section, here’s a complete version of the sample app in Playground you can refer to.

Step 7: Do Cool Stuff

In this article we looked at how to get up and running with NativeScript and Kinvey fast. But we’re only scratching the surface of what these two technologies can do.

Now that you have the basics in place, you’re ready to dive deeper and leverage some of the powerful functionality Kinvey has to offer. Specifically, you might want to check out the following:

  • FlexServices—FlexServices are low code, lightweight Node.js microservices that are used for data integrations and functional business logic. They’re a great way to add custom logic to your apps without needing to worry about infrastructure, deployment, scaling, or maintenance.
  • Push notifications—Kinvey makes it easy to configure and send push notifications in your iOS and Android applications.
  • File storage—Kinvey lets you store and retrieve files up to 5TB in size, and serves them using a Content Delivery Network (CDN) for performance.
  • And more—Kinvey can do a lot, so make sure to check out the Kinvey documentation for a full list of just what’s possible.

So what are you waiting for? If you haven’t already, sign up for a free Kinvey account, visit the NativeScript Playground, and start building awesome apps.

And if you want to learn more, don't forget to register for the upcoming Getting Started with Kinvey webinar.

tj-vantoll

TJ VanToll

TJ VanToll is a frontend developer, author, and a former principal developer advocate for Progress.

Comments

Comments are disabled in preview mode.
Topics

Sitefinity Training and Certification Now Available.

Let our experts teach you how to use Sitefinity's best-in-class features to deliver compelling digital experiences.

Learn More
Latest Stories
in Your Inbox

Subscribe to get all the news, info and tutorials you need to build better business apps and sites

Loading animation