Tag Archive for: ios

Removing platform specific code with webpack in your NativeScript application

The NativeScript framework automatically includes source files that are suffixed with the given platform name. This way the clutter and size of your built application is decreased and you do not distribute dead platform specific code that isn’t needed. But often there are case where is it much more simple to write your platform specific code in a single file and just surround it with if statements for the platform, rather then separating it into separate platform specific files. So what happens then? Let’s take an example – bellow you will see the natvigatingTo event handler for a page which has some platform specific code:

import { EventData } from "data/observable";
import { isIOS, isAndroid } from "platform";
import * as frame from "ui/frame";
import { Page } from "ui/page";
import { HelloWorldModel } from "./main-view-model";

export function navigatingTo(args: EventData) {
    let page = <Page>args.object;

    if (isIOS) {
        console.log("test");
        frame.topmost().ios.controller.view.window.backgroundColor = UIColor.colorWithRedGreenBlueAlpha(242 / 255, 242 / 255, 242 / 255, 1);
        UITableViewCell.appearance().selectionStyle = UITableViewCellSelectionStyle.None;
        UITableView.appearance().tableFooterView = UIView.alloc().initWithFrame(CGRectZero); // Hide empty cells
    }

    console.log(`We are running on ${isAndroid ? "ANDROID" : "IOS"}`);

    page.bindingContext = new HelloWorldModel();
}

If we run that though webpack with uglify (and you should always do that for the version of an app that you publish to the stores) we will get this (note that I reformatted code with new lines for readability):

function i(e) {
    var t = e.object;
    o.isIOS && (
        console.log("test"),
        a.topmost().ios.controller.view.window.backgroundColor = UIColor.colorWithRedGreenBlueAlpha(242 / 255, 242 / 255, 242 / 255, 1),
        UITableViewCell.appearance().selectionStyle = 0,
        UITableView.appearance().tableFooterView = UIView.alloc().initWithFrame(CGRectZero)
    ),
        console.log("We are running on " + (o.isAndroid ? "ANDROID" : "IOS")),
        t.bindingContext = new r.HelloWorldModel
}

As you see, although changed a bit, all the platform specific code is there. And no matter if you bundle for iOS or Android the code will be the same. Since you cannot change the platform during runtime some parts of that code are dead and will never execute. So how can we remove those? This can easily be achieved by helping webpack “understand” which parts of the code are dead so it can remove them when it optimizes the bundle.

First thing that we will do is instead of using the isAndroid / isIOS flags from the platform module, we will use flags that we will define in the global object (you will see why later on). In the app’s entry point before starting it we will extend the global object with the flags and their values:

import { isIOS, isAndroid } from "platform";
Object.assign(global, { isIOS, isAndroid });

Now in order to make TypeScript happy and so that we can directly use ‘global.isIOS’ and ‘global.isAndroid’ lets add an ‘app.d.ts’ in our app with the following content:

// Augment the NodeJS global type with our own extensions
declare namespace NodeJS {
    interface Global {
        // Add custom properties here.
        isIOS: boolean;
        isAndroid: boolean;
    }
}

This extends the definition of the global object that is provided with NativeScript’s core modules and we won’t have to cast global to any in order to make our code compile.

Now if we refactor our platform specific code to use the global object instead, the code will look like this:

export function navigatingTo(args: EventData) {
    let page = <Page>args.object;

    if (global.isIOS) {
        console.log("test");
        frame.topmost().ios.controller.view.window.backgroundColor = UIColor.colorWithRedGreenBlueAlpha(242 / 255, 242 / 255, 242 / 255, 1);
        UITableViewCell.appearance().selectionStyle = UITableViewCellSelectionStyle.None;
        UITableView.appearance().tableFooterView = UIView.alloc().initWithFrame(CGRectZero); // Hide empty cells
    }

    console.log(`We are running on ${global.isAndroid ? "ANDROID" : "IOS"}`);

    page.bindingContext = new HelloWorldModel();
}

If we run webpack with uglify now we wont see much of a difference. This is because webpack still does not know which code is dead. So lets help him understand that by changing the webpack.config.js and adding to the webpack.DefinePlugin the same global.isIOS and global.isAndroid flags. This is possible because during bundle time webpack already knows for which platform it is creating the bundle:

// Define useful constants like TNS_WEBPACK
new webpack.DefinePlugin({
    "global.TNS_WEBPACK": "true",
    "global.isAndroid": `${platform === "android"}`,
    "global.isIOS": `${platform === "ios"}`,
    "process": undefined,
}),

When the bundle is created webpack will replace the occurrence of those two flags with the respective value as defined in the config file. By doing this it will render parts of the code dead and the UglifyJS plugin can safely remove them from the final bundle.

One last thing to do – since we will not actually need the flags in the global object when the code is bundled, we can safely change the code in the app entry point:

if (!global.TNS_WEBPACK) {
    Object.assign(global, { isIOS, isAndroid });
}

This will ensure that both bundled and non-bundled builds are working as expected and we will not be polluting the global object unnecessary.

Now if we bundle and uglify the code, for iOS we will get (again code reformatted for readability):

function r(e) {
    var t = e.object;
    console.log("test"),
        o.topmost().ios.controller.view.window.backgroundColor = UIColor.colorWithRedGreenBlueAlpha(242 / 255, 242 / 255, 242 / 255, 1),
        UITableViewCell.appearance().selectionStyle = 0,
        UITableView.appearance().tableFooterView = UIView.alloc().initWithFrame(CGRectZero),
        console.log("We are running on IOS"),
        t.bindingContext = new a.HelloWorldModel
}

And for Android we will get:

function a(t) {
    var e = t.object;
    0;
    console.log("We are running on ANDROID");
    e.bindingContext = new o.HelloWorldModel
}

As you will notice the code for both platforms is greatly optimized now. First the conditional expression we had in the last console.log is changed so there is no unnecessary comparison. Furthermore for Android all the iOS specific code has been removed and replaced with a dummy 0.

Implementing In-App purchases in your NativeScript application (Part 2)

In the previous part I’ve shown you how to create a small NativeScript application and add a simple purchase workflow using the nativescript-purchase plugin. Now it is time to wire things for iOS. In this part I will guide through adding the necessary settings on the Apple Developer portal and iTunes Connect, create some sandbox users and test your workflow.

Creating an App ID

The first thing we need to do is register a new App ID in the Apple Developer portal. We do this in the “Certificates, IDs & Profiles” menu, then “App IDs” and click on the “plus” button on the top right. For the App ID, you can select whatever description you want. For the App ID Suffix you must select Explicit App ID and type exactly the name as it is present in the package.json file nativescript section the id attribute. In my case this is org.nativescript.purchasesample. And we need to use Explicit App ID, because wildcard App IDs do not support in-app purcahses.
App ID Setup

Configuring iTunes Connect

Once we have the App ID set up we need to head over to iTunes Connect and add our application there. Note that even if you intend to do Sandbox testing only, you still need to register your app in iTunes Connect. You do not need to upload the app binary or wait for Apple’s approval, it just needs to be registered.
On the New App screen we select iOS and fill in the rest of the details. For Bundle ID make sure you select the bundle that we have just created.
iTunes Connect App Add

NB: It can take up to couple of minutes for iTunes Connect to pick up your new App ID. So if you do not see it in the drop down, don’t worry, just wait 5-10 minutes and it should appear.

Once we have our App created we need to go the App settings screen Features -> In-App Purchases. This is where we will add our products.
iTunes Connect In-App Purchases

Since we are going to do Sandbox testing, you can safely ignore the Information about production products. When we press the plus button to add our first product we are presented with the following wizard that asks us what type of product we will add.
iTunes Connect Add Product

As of writing of this post the nativescript-purchase plugin supports only in-app purchases. So we will be working with the first 2 options. We will create one consumable and one non-consumable products.
We will start by adding a consumable product first. On the New In-App Purchase screen we go and enter the details for our product. When we created the application in the previous part of the tutorial we have said that our consumable product will be product2. So let’s fill in the details for that product:
iTunes Connect In-App Purchase Setup
Reference Name – You can use anything for this. This is not shown to the end user and is only for internal use.
Product Id – This one is very important. You must use the same ID that we used in the init() method of the nativescript-purchase plugin. In our case (and in case you followed the naming from the first part) we should input here org.nativescript.purchasesample.product2.
Pricing – You should select here the pricing tier for this product. You can chose from various ones and select the one that best suits your needs.
Localization (Display Name and Description) – This is what the user will see when you list your products. You can add localized text for both by pressing the plus sign next to the Localization header.

Once we save Product 2 info, we have to go through the above procedure and add Product 1 as well. Note that Product 1 will be a non-consumable product, so make sure you select the second option in the add product popup.

Now let’s return to our NativeScript project and run the app onto the simulator. If we did everything correctly we should see a nice list of products that we just added to iTunes Connect:
Purchase List Simulator

NB: You might NOT be able to see the registered products (consumable, non-consumable, etc.) if you do not have any contracts in effect regarding paid applications. To solve the problem, you can activate the contract for paid applications in App Store Connect > Contracts, Tax and Banking section.

Testing with Sandbox purchases

Now that we have the list ready it is time to do some sandbox purchases and test our purchase workflow. Before we start you must note the following: you cannot make sandbox (or real) purchases in the simulator! So in order to test we must deploy to a real device and in order to do this we first need to set up a provisioning profile. So lets get back to the Apple Developer portal and create a Development provisioning profile for the App ID we created at the start:
Provision Profile Creation Screen

Once you generated the provision profile and download it locally it is time to assign it to our app. In order to do so first do a tns build ios in the terminal in order NativeScript to generate fully the platform specific files. Then in Finder navigate to the platforms/ios folder located under you project’s root folder and open the .xcodeproj file. This should bring up XCode. There click on your project in the left pane and then uncheck the “Automatically manage signing” box and then in the “Signing (Debug)” section import your downloaded provision profile.
XCode Provisioning Setup

Do not close XCode yet as we still need to add the in-app purchase entitlement to the project. Go to the Capabilities section and turn on the In-App Purchase capability. Wait till all actions are complete and then you can close XCode.
XCode In-App Purchase Entitlement

Now we are ready to deploy the app to our real device. Attach your device and then use tns deploy ios to deploy to it. Once the app is deployed, open it and if everything is done correctly you should see the same list of products as in the simulator.
NB: You need to repeat the two XCode steps above every time you do tns platform clean ios on when you upgrade the NativeScript runtime to a new version. This is because those actions recreate the whole platforms/ios folder and its files.

The only thing left is to set up some sandbox users to test our purchases. Apple has a really nice step-by-step guide on how to add your sandbox users to your iTunes Connect account, so I will not go in much details here. The most important thing to remember is that you cannot use your actual Apple ID as a sandbox user. You must set up a new one.
Once you have added your sandbox users go to the App Store app on your device, scroll down to the bottom of the Featured page and tap on your Apple ID and select Sign Out. Do not try to sign in with the sandbox user to the App Store app as you will get an error. Instead go to the sample app we are developing and tap on a product. You will get a prompt asking you to sign in:
Device In-App Purcahse Prompt
Tap on the Use Existing Apple ID option and enter your sandbox user credentials:
Device Sandbox User Sign In
You will get a prompt to confirm your sandbox purchase:
Device Sandbox In-App Purchase Confirm
Once you press Buy and wait for the purchase to complete you will get a prompt of the successful purchase:
Device Sandbox In-App Purchase Success
Congratulations you have just made your first sandbox purchase!

If you want to explore all the properties you can get from the nativescript-purchase plugin for the Product and Transaction you can add some console.logs to the purchase workflow methods we have added in the previous part of the tutorial. Attach your device to your Mac and then use tns run ios so you can see the logs in your terminal.

Coming up next

In the final part of this three part tutorial I will guide you through configuring things for Android on Google Play and making some sandbox purchases on Android.

Implementing In-App purchases in your NativeScript application (Part 1)

Many mobile applications nowadays leverage the in-app purchase capabilities of both Android and iOS which gives users ability to buy digital goods. But since there are some tricks to get the native part going I’ve decided to write a 3-part in depth tutorial that will guide you through the full process of setting up in-app purchases in your NativeScript app. So let’s get going!

Creating the sample application

As of the writing of this article the most recent NatvieScript version is 2.5.1. Make sure you have installed and configured it correctly. For this tutorial we will be using vanilla TypeScript app so let’s run the following and create it:

tns create purchase-sample --tsc

Adding the nativescript-purchase plugin

After we created our sample app it is time to add the nativescript-purchase plugin. The plugin will do the heavy lifting of consuming in-app purchases in our application:

tns plugin add nativescript-purchase

Configuring available purchases for the application

Now it is time to start wiring things in our application. First stop is to specify what purchases will be available to our users. This is done in the app.ts file of the application (the main entry point of the NativeScript app). You can do this by adding the following block just above the app.start(...) line:

import * as purchase from "nativescript-purchase";

purchase.init([
    "org.nativescript.purchasesample.product1",
    "org.nativescript.purchasesample.product2"
]);

With this we are telling that products with ids org.nativescript.purchasesample.product1 and org.nativescript.purchasesample.product2 should be available to the users. Note that it is not necessary to prefix your products’ ids with the application id but this makes it really clear what product with which application is associated. If you do not like those long ids you can use just product1 and product2. Just note what ids you use here as we will need them in the next parts of the tutorial when we set up everything in iTunes Connect and Google Play Store.

Designing the UI

Now let’s move on to creating a simple UI that will show a list of products and give users ability to buy new products or restore their previous purchases (in case they changed their device):

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" class="page">
    <Page.actionBar>
        <ActionBar title="In-App Purchase Sample" class="action-bar">
            <ActionBar.items>
                <ActionItem ios.position="right" text="Restore" tap="onRestoreTap"/>
            </ActionBar.items>
        </ActionBar>
    </Page.actionBar>

    <GridLayout>
        <ListView items="{{ items }}" itemTap="onProductTap">
            <ListView.itemTemplate>
                <GridLayout rows="auto, auto" columns="*, auto" padding="5">
                    <Label row="0" col="0" class="h2" text="{{ localizedTitle }}"/>
                    <Label row="1" col="0" text="{{ localizedDescription }}" textWrap="true" color="#999999"/>
                    <Label text="{{ priceFormatted }}" row="0" rowSpan="2" col="1" class="h1" style="margin-left: 5"/>
                </GridLayout>
            </ListView.itemTemplate>
        </ListView>
        <ActivityIndicator busy="{{ loading }}" />
    </GridLayout>
</Page>

The UI is quite simple: we have an action bar with a button to restore previous purchases. Then bellow we have a list view that will display the available purchases and when tapped we will trigger our purchase workflow.Finally we have an activity indicator to show the user when we are doing some backend operations.

Purchase workflow code

With the setup and the UI ready it is time to go in the main-page.ts file and write the actual purchase workflow code that we will use to show the available products to the user and allow the user to buy and restore their purchases.
We will start by adding some required imports at the top for things that we will need:

import * as applicationSettings from "application-settings";
import * as purchase from "nativescript-purchase";
import { Transaction, TransactionState } from "nativescript-purchase/transaction";
import { Product } from "nativescript-purchase/product";
import { ItemEventData } from "ui/list-view";

let viewModel: Observable;

The next step will be to add the code that will load our products and put them in the model for the page.:

export function navigatingTo(args: EventData) {
    let page = <Page>args.object;

    viewModel = new Observable({
        items: [],
        loading: true
    });

    page.bindingContext = viewModel;

    purchase.getProducts()
        .then((res) => {
            viewModel.set("items", res);
            viewModel.set("loading", false);
        })
        .catch((e) => console.log(e));
}

NB: For simplicity we are be using a local model for the page that is defined in the same TS file. In a real life scenario you should always separate your models from the code behind of the view!

We set some default values in the model and bind it to the page. Next we call the getProducts() method of the nativescript-purchase plugin that will load our product details from iTunes Connect/Google Play Store – like price, title, etc. You can check all the available product properties here. The method will return an array with the products, which we set in the model and stop the loading animation.

There is one more thing that we should do in the navigatingTo event handler – to subscribe to the exposed transactionUpdated event of the nativescript-purchase plugin where we will handle the transactions made by our users. You can add this at the end of the navigatingTo event handler:

purchase.on(purchase.transactionUpdatedEvent, (transaction: Transaction) => {
    if (transaction.transactionState === TransactionState.Restored) {
        applicationSettings.setBoolean(transaction.productIdentifier, true); /* 1 */
    }
    if (transaction.transactionState === TransactionState.Purchased) {
        if (transaction.productIdentifier.indexOf(".product2") >= 0) { /* 2 */
            purchase.consumePurchase(transaction.transactionReceipt) /* 3 */
                .then((responseCode) => {
                    if (responseCode === 0) {
                        // Provision your user with their digital goods bought. 
                    }
                })
                .catch((e) => console.log(e));
        }
        else {
            applicationSettings.setBoolean(transaction.productIdentifier, true); /* 4 */
        }
    }    
});    

A nice way to store locally what products are purchased is to use NativeScript’s application-settings module. This way you can add a key in the application settings for any product bought by the user and then you can enable/disable specific parts of your application depending on what the user has purchased. So in lines /* 1 */, after a purchase is restored, and on /* 4 */, when the user has purchased a product, we set the product id in the application settings. The special case for product2 on line /* 2 */ is because we will be setting up product2 as a consumable purchase. There are differences of how consumable purchases work on iOS and on Android. For iOS consumable purchases are automatically consumed after a successful purchase, so the user can make another one right away. For Android you are responsible for consuming a purchase and flag it for repurchase. That’s why on line /* 3 */ we call the consumePurchase() method. If the consume is successful and the return code is 0 you should provision your users with the digital goods corresponding to the product bought. Note that for iOS this method always returns response code 0.
In case you have many consumable purchases you can add some suffix to the product id (for example .consumable) so you can easily distinguish for what products you should call the consumePurchase() method.
In this event handler you also have access to various other properties of the transaction which you can use (for example for extended verification of the transaction on your backend server with Apple/Google). You can check the full list of available properties here.

Finally we should add our handlers for the restore button tap and the tap on the product that should trigger a purchase:

export function onProductTap(data: ItemEventData) {
    let product = viewModel.get("items")[data.index] as Product;

    purchase.buyProduct(product);
}

export function onRestoreTap() {
    purchase.restorePurchases();
}

NB: For the buyProduct() method it is really important that you pass the product instance as returned by the getProducts() method. If you just create a new product and populate its properties the method will fail on iOS!

Up next

If you go ahead and run the code now, you should get a nice empty list 🙂 This is because we need to configure the products on iTunes Connect and Google Play Store.
In the next part of this tutorial I will guide through the setup on iTunes Connect and then we will run our sample application on iOS and make some sandbox purchases! So stay tuned!