A NativeScript Azure Mobile Apps plugin.
Installation
Run the following command from the root of your project:
tns plugin add nativescript-azure-mobile-apps
This command automatically installs the necessary files, as well as stores nativescript-azure-mobile-apps as a dependency in your project's package.json file.
Configuration
For most of the functions the plugin you only need to know the name of your Azure mobile apps portal. The only thing that requires additional configuration is the social sign-in under iOS. For that please follow the steps explained below
Starting with version 2.0, due to updated libraries, Mircososft now reqiures the minimum SDK for Android to be 19. So you need to adjust 2 files in your app:
- In the
app/App_Resources/Android/AndroidManifest.xml
you must haveandroid:minSdkVersion
set to 19 or above. - In the
app/App_Resources/Android/app.gradle
you must ensure that in yourdefaultConfig
you haveminSdkVersion
set to the same number as the one you set in theAndroidManifest.xml
file. So assuming you are setting it to 19, your file should look something like this:
android { defaultConfig { generatedDensities = [] applicationId = "......" minSdkVersion 19 } }
API
MobileServiceClient
Static Methods
- configureClientAuthAppDelegate(): void
Configures the iOS authentication delegate. You are required to call this before your applications starts in case you will be using social sign in under iOS!
Methods
-
onstructor(string)
Initialize a new client with the given Azure portal url. -
getTable(string): MobileServiceTable
Gets a reference to the table with the given name. -
login(AuthenticationProvider, string?): Promise
Performs a social sign in with the given provider and url scheme. -
loginFromCache(): boolean
Tries to login the user from a previously cached authentication. Returnstrue
if successful.
Properties
-
user - MobileServiceUser
Returns the currently social signed in user. -
push - MobileServicePush Returns a
MobileServicePush
object which you can use to work with push notifications.
MobileServicePush
Methods
-
register(string): Promise
Registers the given native push token for push notifications with Azure. -
registerWithTemplate(string, string, string): Promise
Registers the given native push token, template name and template for push notifications with Azure. For more information about templates see the usage below. -
registerWithTags(string, string[]): Promise
Registers the given native push token for push notifications with Azure and associates the given tags with the device installation. You can read more about tags here. -
registerWithTagsAndTemplate(string, string[], string, string): Promise
This combines the above 2 methods, so you can register both with a template and tags. -
unregister(): Promise
Unregisters the device from Azure push notifications.
Properties
- installationId - string
Returns the
installationId
of the device what is registered with Azure's Notification Hubs. This is usefull, for example, in case you need custom tags and you need to call your backend to add the tags.
MobileServiceUser
Static Methods
-
clearCachedAuthenticationInfo(): void
Clears the previously cached authentication info. -
getFromCache():MobileServiceUser
Returns the previously cached user.
Methods
- getProviderCredentials(): Promise
Returns various details about the current user (for example surname, given name, user id, claims, etc.).
Properties
-
userId - string
Gets the user id for this user. -
authenticationToken - string
Gets the OAuth token for this user.
MobileServiceTable
Methods
-
read(): Promise<Array>
Returns all records in the table. -
insert(T): Promise
Adds the given item to the table. Returns thie updated item (for example with id assigned). -
update(T): Promise
Updates a given item in the table. Returns the updated item. -
deleteById(number|string): Promise
Deletes the item with the given id from the table. -
deleteItem(T): Promise
Deletes the given item from the table. -
where(): MobileServiceQuery
Returns a query object which you can use to filter, order and page through the data in the table.
MobileServiceQuery
The query object provies a very easy to use chainable interface to filter, order and page through the data inside a table.
Methods
-
field(string): this
Specifies that we will be filtering by the given field. After this you can apply one of the filtering operations. -
eq(string|number|boolean|Date): this
Filters the table by a previously specifiedfield
so that its value equals the given value. -
ne(string|number|boolean|Date): this
Filters the table by a previously specifiedfield
so that its value is different than the given value. -
gt(string|number||Date): this
Filters the table by a previously specifiedfield
so that its value is greater than the given value. -
ge(string|number||Date): this
Filters the table by a previously specifiedfield
so that its value is greater than or equal to the given value. -
lt(number||Date): this
Filters the table by a previously specifiedfield
so that its value is lower than the given value. -
le(number||Date): this
Filters the table by a previously specifiedfield
so that its value is lower than or equal to the given value. -
startsWith(string, string): this
Filter the table by the given field so that the values start with the given value. -
endsWith(string, string): this
Filter the table by the given field so that the values end with the given value. -
and(): this
Applies a logcalAND
operator after which you can start another filter condition. -
or(): this
Applies a logcalOR
operator after which you can start another filter condition. -
orderBy(string, SortDir): this
Orders the resultset by thegive field and direction. This should be applied after specifying your filters! -
skip(number): this
Skips the given number of records from the current resultset. This should be applied after all fitlers and sorting. -
top(number): this
Takes only the given amount of records from the resultset. This should be applied after all fitlers and sorting. -
read(): Promise
Reads and returns the records of the currently filtered, ordered and windowed resultset.
Usage
Note that there is no difference in using the plugin in Angular NativeScript apps, so the usage below is valid for Angular apps as well.
Create a client
;;
Get a reference to a table
;
Get all items in a table
todoItemTable.read.then;
Add an item to a table
;item.text = "NativeScript Rocks!";todoItemTable.insertitem.then;
Update an item
item.text = "Changed Text";todoItemTable.updateitem.then;
Delete an item
todoItemTable.deleteItemitem.then;
Delete an item by ID
todoItemTable.deleteById"some id".then;
Query table
todoItemTable.where.field"completed".eqtrue.read.then;
Sorting
;todoItemTable.where.field"completed".eqtrue.orderBy"createdAt", SortDir.Desc.read.then;
Paging
;todoItemTable.where.field"completed".eqtrue.orderBy"createdAt", SortDir.Asc.skip2.top3.read.then;
User Authentication (Social Sign In)
iOS login requirements
In versions 1.0.0 and lower login on iOS leveraged an in-app browser. This will be banned so we needed to switch to SafariViewController which is not "in-app". So we need to be able to switch back and forth between the external browser. The main benefit is this browser can leverage cookies already set by for instance a Facebook login, so the user doesn't have to enter his credentials again.
It's a bit of work, but it's a one time effort and should take you about 5 minutes to complete these steps:
Custom URL Scheme
Switching to the external browser is not a problem, but switching back requires you to configure a 'Custom URL Scheme'.
Open app/App_Resources/iOS/Info.plist
and add:
CFBundleURLTypes CFBundleTypeRole Editor CFBundleURLName my.bundle.id CFBundleURLSchemes x-msauth-tns-azure-sample
Make sure the Custom URL Scheme string x-msauth-tns-azure-sample
above is unique on the device of the user,
so including your bundle id would be a good start (replace the dots by dashes).
Also, replace my.bundle.id
by your bundle id.
Add ALLOWED EXTERNAL REDIRECT URLS
Add x-msauth-tns-azure-sample://easyauth.callback
to the 'ALLOWED EXTERNAL REDIRECT URLS' field in these screenshots of your Azure backend.
Make sure to replace x-msauth-tns-azure-sample
by your own Custom URL Scheme.
App Delegate wiring
Now that your app can be called from the external party it still can't switch back to the foreground unless
you wire up a method in the App Delegate. Don't worry, this plugin takes care of that for you, the only thing
you need to do is add this line just before app.start()
in app.js
/ app.ts
:
// add thisMobileServiceClient; // something like this is already thereapplicationstart moduleName: "main-page" ;
login
Passing the URL Scheme to Note that calling login
has changed a bit; you now need to pass a second parameter to this function to use the
new login mechanism. Failing to do so will fall back to the deprecated in-app browser authentication method.
Make sure to replace x-msauth-tns-azure-sample
by the scheme you configured in Info.plist
before.
You can leave it out if you only target Android.
;client.loginAuthenticationProvider.Google, "x-msauth-tns-azure-sample".then,;
Once authenticated the userId and token are cached so you can login by simply calling:
client.loginFromCache; // Will return true if there are cached credentials and will setup the client accordingly
If you want to get additional information about the user (like provider token, name, email, profile photo etc.) you can do this by calling getProviderCredentials()
:
client.user.getProviderCredentials.then;
Note: Since each provider provides different amount of details (also depends on what you have authorized in the Azure portal),
if you are looking for some specific information, you should check the claims
property of the result.
It is a dictionary containing all the information that is returned from Azure.
If you want to remove the cached authentication info you should use:
;MobileServiceUser.clearCachedAuthenticationInfo;
Push Notifications
NOTE: In order to work with push notifications you also need to install the nativescript-push-notifications
plugin.
You can do this by running the following command:
tns install nativescript-push-notifications
You can read more on how to use the push plugin here.
Register
You need to call the push register with Azure in the success callback of the push plugin by passing the registration token returned by the push plugin.
pushPlugin.registerpushSettings,,;
Register with a template
If you want to use a custom template for the notifications, you can use the registerWithTemplate
method to pass
your template name and body.
;pushTemplates = "{\"data\":{\"message\":\"$(param)\"}}";pushTemplates = "{\"aps\":{\"alert\":\"$(param)\"}}"; pushPlugin.registerpushSettings,,;
Unregister
pushPlugin.unregister,console.loge, pushSettings;
Demos
This repository includes a plain NativeScript demo. In order to run it execute the following in your shell:
$ git clone https://github.com/peterstaev/nativescript-azure-mobile-apps$ cd nativescript-azure-mobile-apps$ npm install$ npm run demo-ios
This will run the plain NativeScript demo project on iOS. If you want to run it on Android simply use the -android
instead of the -ios
sufix.
Donate
bitcoin:14fjysmpwLvSsAskvLASw6ek5XfhTzskHC