Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Send SMS Text Messages In NativeScript With Angular

TwitterFacebookRedditLinkedInHacker News

Not too long ago I wrote a tutorial titled, Use Social Media Sharing Prompts in a NativeScript Angular Application, which demonstrated how to share content from the device. The sharing included locations like Facebook, Twitter, and anything else the platform found appropriate. This included SMS text messages.

Social sharing functionality isn’t the only way to access the messaging and dialing features of an Android and iOS device.

We’re going to see how to send SMS text messages in Android and iOS via an application built with NativeScript and Angular.

Before you get too far into this tutorial, it is important to note that this functionality cannot be tested via the Android and iOS simulators. The simulators do not have the necessary messaging features baked into them. All testing must be done with a physical device.

NativeScript SMS Text Messaging

The above image illustrates what we’re trying to build. A simple application where we can specify a mobile recipient and a message to send.

Create a New NativeScript with Angular Project

For simplicity, we’re going to create a new NativeScript project that uses Angular. From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

tns create sms-project --ng

The above command will create a new project. The --ng flag indicates that the project will use Angular rather than Vue.js or Core.

To make sending messages possible, a plugin is necessary. From the command line, execute the following:

tns plugin add nativescript-phone

The above command will install a plugin called nativescript-phone that supports SMS text messages and dialing.

With more recent versions of Android and iOS comes stricter permission control. For this reason we’ll have to make some changes, otherwise all attempts to use SMS and dialing will be rejected.

Open the project’s app/App_Resources/Android/AndroidManifest.xml and include the following two lines:

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

The above lines will affect Android. We also need to make some changes for iOS. Open the project’s app/App_Resources/iOS/Info.plist and include the following:

<key>LSApplicationQueriesSchemes</key>
<array>
   <string>tel</string>
   <string>telprompt</string>
</array>

At this point we can start developing the application by applying XML and TypeScript.

Including the UI and Logic for Sending SMS Text Messages

It makes sense to have a form for user input before sending the user input as an SMS text message. Before we start designing the UI, we should probably come up with the TypeScript logic that powers the application.

Open the project’s app/app.component.ts file and include the following:

import { Component } from "@angular/core";
import * as TNSPhone from 'nativescript-phone';

@Component({
    selector: "ns-app",
    templateUrl: "app.component.html",
})
export class AppComponent {

    public input: any;

    public constructor() {
        this.input = {
            recipient: "",
            message: ""
        }
    }

    public send() {
        if(this.input.recipient != "" && this.input.message != "") {
            TNSPhone.sms([this.input.recipient], this.input.message).then(result => {
                    console.dir(result);
                    this.input.recipient = "";
                    this.input.message = "";
                }, error => {
                    console.dir(error);
                });
        }
    }

}

There is a decent amount happening above so we should probably break it down.

First we need to import the plugin that we had previously downloaded via the command line:

import * as TNSPhone from 'nativescript-phone';

At some point in time we’ll be binding an object to the UI. For this reason we create the input object and initialize it within the constructor method. Provided the input properties are not empty strings, the send method will make use of the nativescript-phone plugin.

public send() {
    if(this.input.recipient != "" && this.input.message != "") {
        TNSPhone.sms([this.input.recipient], this.input.message).then(result => {
                console.dir(result);
                this.input.recipient = "";
                this.input.message = "";
            }, error => {
                console.dir(error);
            });
    }
}

If the message is sent successfully, the input variable that represents the form is reset.

Now let’s take a look at the simple XML based UI. Open the project’s app/app.component.html file and include the following:

<ActionBar title="{N} SMS Example"></ActionBar>
<StackLayout class="form">
    <StackLayout class="input-field">
        <Label text="Recipient (Mobile)" class="label font-weight-bold m-b-5"></Label>
        <TextField class="input" [(ngModel)]="input.recipient"></TextField>
        <StackLayout class="hr-light"></StackLayout>
    </StackLayout>
    <StackLayout class="input-field">
        <Label text="Message" class="label font-weight-bold m-b-5"></Label>
        <TextField class="input" [(ngModel)]="input.message"></TextField>
        <StackLayout class="hr-light"></StackLayout>
    </StackLayout>
    <StackLayout class="input-field">
        <Button text="Send" class="btn btn-primary" (tap)="send()"></Button>
    </StackLayout>
</StackLayout>

Most of the XML above is taken from the NativeScript theming documentation. Notice that the input variable is bound to the form and likewise the send method is bound to the button.

Conclusion

You just saw how to send SMS text messages in a NativeScript Android and iOS application that uses Angular. If you wanted to send a message to multiple recipients, the plugin supports an array of phone numbers. The plugin also supports dialing phone numbers, not just sending SMS text messages.

Depending on the device and platform, this plugin may open the default messaging application and pre-populate it with the data passed via the plugin. Do not anticipate that messages will be sent from the background.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.