Build an Ionic Plugin With Couchbase Lite on iOS
In this tutorial, you will learn how to use Couchbase Lite in a Cordova application for iOS.
Join the DZone community and get the full member experience.
Join For Freein this tutorial, you will learn how to use couchbase lite in a cordova application.
the sample project is a cordova web application that allows users to query for and display a list of hotels stored in a couchbase lite database.
architecture
the user interface is a web app written in javascript using ionic and is rendered within a webview. the business logic and data model is written in native swift. the data model uses couchbase lite as the embedded data persistence layer. the cordova plugin api acts as the bridging layer between the javascript and the native swift worlds. the plugin exposes a javascript api to the web app.
this architecture allows you to write the user interface code once for both ios and android apps while leveraging couchbase lite’s native ios framework for data management.
data model
the data model for the app is very straightforward. there is one type of document: the
"hotel"
document which contains the details of each hotel. those documents have a
"type": "hotel"
property.
prerequisites
this tutorial requires the following components and versions to run successfully.
- xcode 10 or above
- swift 4.2
- couchbase lite 2.1.1
the tutorial also assumes that the reader has a basic understanding of developing apps with cordova and swift.
getting started
the user interface has already been implemented in the starter project. you will add the code to persist and query data.
-
install the ionic and cordova clis which are tools that are required for building and managing ionic and cordova based apps.
npm install -g ionic cordova
- download the starter project .
- unzip starter-project.zip .
- open the starter-project/ directory in the javascript editor of your choice (for example, visual studio code or webstorm ).
- the user interface code is located in hotellister/src/pages/home/ .
-
run the following commands in your terminal.
thecd hotellister npm install
npm install
command installs dependencies. -
to deploy the app to an ios simulator, run the following.
then, use theionic cordova platform add ios ionic cordova emulate --list
--target
option to specify the simulator to deploy the app to.ionic cordova emulate ios --target "iphone-xr, 12.0" -- --buildflag="-usemodernbuildsystem=0"
-
you should see an empty list view as shown below.
in the next section, you will setup the cordova plugin which is the first step for establishing communication between native code and javascript.
cordova plugin setup
with cordova plugins , you can write native code and have access to it from javascript. plugins provide access to device and platform functionality that is ordinarily unavailable to web-based apps.
in this section you will create a new plugin called cordova-plugin-hotel-lister to implement data persistence using couchbase lite’s swift api.
the plugin code will be added to the cordova-plugin-hotel-lister folder which resides alongside the hotellister folder.
the starter project contains a file at cordova-plugin-hotel-lister/src/android/utils.java that will be used in a later section to unzip the pre-built database.
-
create a new file at
cordova-plugin-hotel-lister/plugin.xml
with the following.
<?xml version="1.0" encoding="utf-8"?> <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-hotel-lister" version="0.0.1"> <name>cordova-plugin-hotel-lister</name> <description>an cordova plugin for the hotel lister application to implement data persistence using couchbase lite.</description> <license>couchbase ce / https://www.couchbase.com/binaries/content/assets/website/legal/ce-license-agreement.pdf</license> <engines> <engine name="cordova" version=">=3.0.0"/> </engines> <js-module src="www/hotel-lister.js" name="hotellister"> <clobbers target="window.plugins.hotellister" /> </js-module> <platform name="ios"> <config-file target="config.xml" parent="/*"> <feature name="hotellister"> <param name="ios-package" value="hotellister"/> </feature> </config-file> <source-file src="src/ios/hotellister.swift"/> </platform> </plugin>
-
the
id="cordova-plugin-hotel-lister"
attribute is the plugin name which will be used later to import it in the ionic project. -
the
<js-module></js-module>
xml tag declares the location of the file that will declare the javascript interface. -
the
<platform name="ios"></platform>
xml tag declares the location of the swift files to hold the native code.
-
the
-
create a new file at
cordova-plugin-hotel-lister/package.json
with the following.
this file describes the plugin.{ "name": "cordova-plugin-hotel-lister", "version": "0.0.1", "description": "a cordova plugin for the hotel lister app.", "cordova": { "id": "cordova-plugin-hotel-lister", "platforms": [ "android", "ios" ] }, "engines": [ { "name": "cordova", "version": ">=3.0.0" } ], "author": "couchbase <mobile@couchbase.com>", "license": "couchbase ce / https://www.couchbase.com/binaries/content/assets/website/legal/ce-license-agreement.pdf" }
-
create a new file at
cordova-plugin-hotel-lister/www/hotel-lister.js
. this file defines the js api with which a cordova/ionic web app may interact with this plugin. generally, this means that the plugin binds to the window element and by doing so, grants access to its parent project through simple javascript references. add the following to your
hotel-lister.js
file:
var exec = require('cordova/exec'); var hotellister = { /* code will be added here later */ }; module.exports = hotellister;
-
create a new file at
cordova-plugin-hotel-lister/src/ios/hotellister.swift
with the following. this file provides the native swift implementation corresponding to the apis defined in
hotel-lister.js
.
the cordova plugin is instantiated when it is first called in the javascipt webview app. the@objc(hotellister) class hotellister : cdvplugin { override func plugininitialize() { } }
plugininitialized()
method includes the startup code. refer to the plugin lifecycle documentation for more details. -
to verify that your plugin is ready to work as expected, you have to install it in your
hotellister
project. to do so, run the following commands from the root of the
starter-project
folder.
if successful, you should see the following in the output.cd hotellister cordova platform rm ios cordova plugin add ../cordova-plugin-hotel-lister/ cordova platform add ios
adding cordova-plugin-hotel-lister to package.json saved plugin info for "cordova-plugin-hotel-lister" to config.xml
couchbase lite setup
next, you will import couchbase lite as a dependency in the xcode project.
- download couchbase lite from here .
- unzip the file.
- open the xcode project located at hotellister/platforms/ios/hotellister.xcodeproj .
-
drag
couchbaseliteswift.framework
from the downloaded folder to the xcode project navigator. be sure to select the
copy items if needed
checkbox.
-
navigate to
project > general > embedded binary
and drag
couchbaseliteswift.framework
over the list.
database setup
in our example, we will start with a pre-built couchbase lite database that contains a bunch of hotel documents. we will make our queries against the documents in this database. note that in a real-world application, the data could be synced down from other couchbase lite clients or from sync gateway in the cloud.
the pre-built database needs to be added to the xcode project.
- download travel-sample.cblite2.zip .
- unzip it.
- drag it over the xcode project navigator. be sure to select the copy items if needed checkbox.
-
we will use the singleton pattern to setup the database instance. create a new file at
cordova-plugin-hotel-lister/src/ios/databasemanager.swift
and insert the following.
you first check if a database named "travel-sample" exists. if it doesn’t exist, the travel-sample.cblite2 database file that was bundled with the app is copied to the default couchbase lite directory. the database is then opened and the database instance is set.import couchbaseliteswift class databasemanager { private static var privatesharedinstance: databasemanager? var database: database let db_name = "travel-sample" class func sharedinstance() -> databasemanager { guard let privateinstance = databasemanager.privatesharedinstance else { databasemanager.privatesharedinstance = databasemanager() return databasemanager.privatesharedinstance! } return privateinstance } private init() { let path = bundle.main.path(forresource: self.db_name, oftype: "cblite2")! if !database.exists(withname: self.db_name) { do { try database.copy(frompath: path, todatabase: self.db_name, withconfig: nil) } catch { fatalerror("could not copy database") } } do { self.database = try database(name: "travel-sample") } catch { fatalerror("could not copy database") } } }
-
when adding a new swift file, it must be referenced in the plugin’s configuration file. insert the following as a child to the
<platform name="ios"></platform>
element in cordova-plugin-hotel-lister/plugin.xml .<source-file src="src/ios/databasemanager.swift"/>
-
next, add the following import statement to the top of
hotellister.swift
.
add the following instance variable to theimport couchbaseliteswift
hotellister
class in hotellister.swift .
import the couchbase lite framework in hotellister.swift .var database: database?
-
then, update the
plugininitialize()
method in hotellister.swift with the following to set thedatabase
instance property.override func plugininitialize() { self.database = databasemanager.sharedinstance().database }
-
to test your changes, you must re-install the cordova plugin from
cordova-plugin-hotel-lister
to
hotellister
. run the following commands from the root of the
starter-project
folder.
cd hotellister cordova plugin rm cordova-plugin-hotel-lister cordova plugin add ../cordova-plugin-hotel-lister/
-
build the project.
the application should run successfully. you will still see an empty screen because at this stage, the couchbase lite database is initialized but you haven’t run any queries to fetch data from the database.ionic cordova emulate ios --target "iphone-xr, 12.0" -- --buildflag="-usemodernbuildsystem=0"
in the next section, you will use this database variable to query hotels from the pre-built database.
listing hotels
in this section, you will add the functionality to list hotels from the database.
-
add the implementation of the
queryhotels
method to cordova-plugin-hotel-lister/src/ios/hotellister.swift .
this method queries for the@objc(queryhotels:) func queryhotels(command: cdvinvokedurlcommand) { let doc_type = "hotel"; let query = querybuilder .select( selectresult.expression(meta.id), selectresult.property("address"), selectresult.property("phone"), selectresult.property("name") ) .from(datasource.database(database!)) .where( expression.property("type") .equalto(expression.string(doc_type)) ) do { let resultset = try query.execute() let resultsetarray = resultset.allresults() var array = [any]() for item in resultsetarray { array.append(item.todictionary()) } let pluginresult = cdvpluginresult(status: cdvcommandstatus_ok, messageas: array) self.commanddelegate.send(pluginresult, callbackid: command.callbackid) } catch { fatalerror(error.localizeddescription); } }
address
,phone
andname
properties of documents where thetype
property ishotel
. -
next, you will update the plugin’s javascript interface. in
cordova-plugin-hotel-lister/www/hotel-lister.js
, replace
/* code will be added here later */
with the following code snippet.queryhotels: function(successcallback, errorcallback) { exec(successcallback, errorcallback, 'hotellister', 'queryhotels'); },
-
you can now call the
queryhotels
method in the ionic project. add the following to theconstructor
method in hotellister/src/pages/home/home.ts .this.platform.ready().then(() => { window.plugins.hotellister.queryhotels((hotels) => { console.log(hotels); this.hotels = hotels; }); });
-
to test your changes, you must re-install the cordova plugin from
cordova-plugin-hotel-lister
to
hotellister
. run the following commands from the root of the
start-project
folder
cd hotellister cordova plugin rm cordova-plugin-hotel-lister cordova plugin add ../cordova-plugin-hotel-lister/
-
build and run.
ionic cordova emulate ios --target "iphone-xr, 12.0" -- --buildflag="-usemodernbuildsystem=0"
-
you should now see the list of hotels.
conclusion
well done! you have learned how to create a cordova plugin to use couchbase lite’s native apis and import the plugin in an ionic project!
you can find a working copy of the completed project in the final project zip file. to build and run the final project:
- follow the instructions outlined in the getting started section
- the instructions in the couchbase lite setup section to integrate couchbase lite into the final project
Published at DZone with permission of James Nocentini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments