cordova

Hey Folks,

Hope you are enjoying the tech post from my blogs, Few days ago i got opportunity to develop the Bluetooth TSL SDK’s Hand held Scanner Cordova plugin for iPhone. And that was exiting work for me. So i decided to write a blog which will show you how can we actually develop a Simple Cordova/PhoneGap plugin in iOS.

This will be very simple yet effective blog. Before moving ahead please keep in mind following pre-requisites.

  • xCode & iPhone Application Knowledge
  • Basic Knowledge of Cordova/PhoneGap
  • NodeJS installed on your MAC
  • Cordova installed on your MAC
  • Basic Knowledge of JavaScript & HTML

So lets dive into our first PhoneGAP / Cordova Plugin development. So here is the basic understanding of why do we need phonegap/cordova plugins and how can we bridge between them.

So Whats the Plugin ? Well Cordova/ PhoneGap is sued for developing hybrid application through extensive use of HTML & JavaScripts. And this apps can be easily deployed into various platforms like iPhone, Android, Windows, Blackberry and many more. But for accessing device hardware specific functionality PhoneGap/Cordova has created Plugins which can convert the JavaScript function call into iPhone/Android/Windows/Blackberry SDK calls.

So we will be learning this today. So lets deep dive into the coding

Step 1 : Create Cordova Project

cordova create plugin com.plugin Plugin
cd plugin/

Step 2 : Add iOS Platform

cordova platform add iOS

Step 3 : Adding Your Plugin into Config.xml

<!-- My custom plugin Start -->

    <feature name="MyResult">

        <param name="ios-package" value="MyResult" />

    </feature>

 <!-- My custom plugin End -->

Step 4 : Creating MyResult.h & MyResult.m classes

Here we need to inherit ‘CDVPlugin’ class into our MyResult.h

#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
@interface MyResult : CDVPlugin
// This will return the file contents in a JSON object via the getFileContents utility method
- (void) calcMe:(CDVInvokedUrlCommand *)command;

@end
#import "MyResult.h"

@implementation MyResult
-(void)calcMe:(CDVInvokedUrlCommand *)command{
    NSDictionary *jsonObj = [ [NSDictionary alloc]
                             initWithObjects:@[@"10" ] forKeys:@[@"result" ]
                             ];
    
    CDVPluginResult *pluginResult = [ CDVPluginResult
                                     resultWithStatus    : CDVCommandStatus_OK
                                     messageAsDictionary : jsonObj
                                     ];
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end

Step 5 : Writing JavaScripts

Here we can call the calcMe function of our MyResult.h class through this syntax of

Cordova cordova.exec(success function, Failure function,Class Name,Function name,Arguments);

 onDeviceReady: function() {
        app.receivedEvent('deviceready');
        app.getReults();
    },

getReults: function(){
        cordova.exec(
                     function callback(data){
                        alert(data.result);
                     },
                     function errorHandler(err) {
                        alert('Error');
                     },
                     'MyResult',
                      'calcMe',
                     []
        );
    }

And your Final index.js file will look like below

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        app.getReults();
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    },
    // Calling our own function
    getReults: function(){
        cordova.exec(
                     function callback(data){
                        alert(data.result);
                     },
                     function errorHandler(err) {
                        alert('Error');
                     },
                     'MyResult',
                      'calcMe',
                     []
        );
    }
};

app.initialize();

Step 6 : You are now Cordova/PhoneGap Developer : Cheers :)

You can download plugin from plugin.

Hope you have enjoyed this tutorial. There is more coming up stay tuned.

Writing Cordova/Phonegap Plugin for iOS

Aadil Keshwani

People call me geek i call myself Coder. I like to explore & learn new things, R&D and Innovation motivates me. By profession i am iPhone Developer but i have sound knowledge of PhoneGap, HTML, CSS3, WordPress, Photoshop, PHP, CodeIgniter, OpenCart. Feel free to contact me for any queries or help in above technologies, i would be more than happy to help you out.

Category: Uncategorized
1678 views