Using native plug-ins for IOS to extend PHONEGAP

Source: Internet
Author: User
Tags string back

This article explores the PhoneGap (also known as Apache Cordova) application native plug-in for Xcode (which targets IOS devices). If you are new to PhoneGap or need to review the basics of PhoneGap, read the PhoneGap getting started with Xcode for IOS before you continue reading this article.

This article alternately uses the terms Cordova and PhoneGap to indicate the same open source application platform, which allows you to create native-installed mobile applications using HTML and JavaScript. The PHONEGAP code base has been migrated to the Apache Software Foundation's open resources, named Cordova. Adobe still distributes it as a PhoneGap name. For more information, see the blog post by Brian Leroux, "What does PhoneGap, Cordova, name matter?" "As Brian said in this article," The only difference is that the name of the download package is different, and this situation will continue for some time.

PhoneGap not only allows you to build user interfaces for native installed mobile applications with WEB technology, but also provides JavaScript-based APIs for you to interact with native device capabilities. By default, PHONEGAP can access media replay between device cameras, accelerometers, file systems, GPS locations, and other features. However, PhoneGap does not reveal every native API that you use within your JavaScript application. If you want PHONEGAP to perform operations other than its default feature set, you can use the PHONEGAP native plug-in model to extend the functionality of the core PHONEGAP API.

PHONEGAP native plug-ins are different from desktop browser plugins, and they give you a way to plug-in custom code to increase the functionality of the PHONEGAP application framework. The PHONEGAP native plug-in allows you to create new custom features in native code and display them to PHONEGAP applications through the PHONEGAP native-javascript Bridge. This means that you can display all native libraries or frameworks for use inside JavaScript-based PHONEGAP applications.
Understanding the structure of the PHONEGAP native plug-in

Before you start writing PHONEGAP native plug-ins, it will be helpful to understand how the PHONEGAP application container can display native operating system functionality to JavaScript-based applications.
All Cordova APIs include the following two related parts: a JavaScript-based interface that can be accessed within your application, and corresponding native classes for performing operations in native code. Typically, JavaScript classes and native classes have APIs that mirror each other, making it easy to trace. The JavaScript class uses the Cordova.exec () function to invoke native code. When it calls Cordova.exec, it can be passed to the result handler function and the error handler function, and a set of parameters are passed to the native code, and the reference is passed to the native class name and the native function name. Cordova will be responsible for managing the communication between JavaScript and native, and you can focus on building your own applications.

To learn more about PHONEGAP native plug-ins, log in to the Cordova wiki to see the source code for that core API. The entire PHONEGAP framework is built on the same schema, where you can learn about this pattern.

Build your first plugin

To start building your first PhoneGap plug-in, you need to create a new PHONEGAP project by following the steps described in the PhoneGap Getting started with Xcode for IOS article. I named my project Myfirstphonegapnativeplugin.
JavaScript class

After you've set up the Hello Xcode project, you're ready to create a JavaScript interface for the native plug-in. You need to create a class using a function that will mirror the logic shown through native code. Under the WWW folder, create a JavaScript file named Helloplugin.js that contains the simple JavaScript class shown below.

[JavaScript]View Plaincopy
    1. var helloplugin = {   
    2. callnativefunction: function  (  
    3. Li class= "alt" >success, fail, resulttype)  {  return cordova.exec (  success, fail,  
    4.  
    5. [Resulttype]);    
    6. }  
    7.  };  


The Helloplugin class contains a function named Callnativefunction that receives a successful callback function, an error callback function, and a resulttype string argument. The Callnativefunction function contains the cordova.exec function, so the actual native code is called. There are no other JavaScript in this class, but you can add JavaScript code here, depending on your needs.

After calling Cordova.exec, you will see the following five parameters:

A successful callback function (a function called when the native code layer successfully responds) references
An error callback function (a function that is called when a native code layer error responds)
A native code class string reference (which I'll cover in more detail below)
A function name string reference that should be called
An array of parameters that will be passed to native code

Keep in mind that code execution between JavaScript and native code layers is not synchronous, so you need to use callback functions and asynchronous coding practices when developing PHONEGAP native plug-ins.
Native class

To create a native code layer, first create a new native Objective-c class that extends the Cdvplugin class of the core Cordova API:

Right-click the Plugins directory within the PHONEGAP project and select New File (see Figure 1).

In the New File Wizard, select the Objective-c class template and click Next (see Figure 2).

Select the Object-c class template.

Type Helloplugin as the name of the new class and take the class as a subclass of Cdvplugin (see Figure 3).

The Cdvplugin class is the parent class that all Cordova classes must extend. The Cdvplugin class encapsulates all the necessary logic required for native JavaScript communication through the PhoneGAP API. The Phonegap.exec function allows you to invoke a function on the new class. The Cdvplugin class contains a core function called Writejavascript that allows you to invoke JavaScript within the PHONEGAP application Web view. All communication in this direction of native to Web JavaScript must be done using the Writejavascript function.

Click Next.
When prompted, specify a location for the new file (preferably in the Plugins directory within the Xcode project), and click Finish to continue.

You will see a new header file (. h) and a new implementation file (. m) within the PHONEGAP project (see Figure 4).

Next, add a definition for the Nativefunction function in your. h file:

[Plain]View Plaincopy
    1. #import <Cordova/CDV.h>
    2. @interface Helloplugin:cdvplugin
    3. -(void) Nativefunction: (nsmutablearray*) arguments withdict: (nsmutabledictionary*) options;
    4. @end


This definition contains the following two parameters: one is Nsmutablearray, which contains the parameters received from the JavaScript layer and the Options dictionary (map). In this case, you only need to focus on the parameter array. The header file contains only method signatures, and you do not need to include any application logic in the. h file.

After you create the class signature, add the logic to the Nativefunction function instance of the. m file. Below you will see an example of the OBJECTIVE-C function used internally by this native plug-in class.

[Plain]View Plaincopy
  1. #import "HelloPlugin.h"
  2. @implementation Helloplugin
  3. -(void) Nativefunction: (nsmutablearray*) arguments withdict: (nsmutabledictionary*) Options {
  4. Get the callback ID
  5. NSString *callbackid = [arguments pop];
  6. NSLog (@ "Hello, this was a native function called from phonegap/cordova!");
  7. NSString *resulttype = [arguments objectatindex:0];
  8. Cdvpluginresult *result;
  9. if ([Resulttype isequaltostring:@ "Success"]) {result = [Cdvpluginresult RESULTWITHSTATUS:CDVCOMMANDSTATUS_OK Messageasstring: @ "Success:)"];
  10. [Self Writejavascript:[result tosuccesscallbackstring:callbackid]]; } else {result = [Cdvpluginresult resultwithstatus:cdvcommandstatus_error messageasstring: @ "ERROR:("];
  11. [Self Writejavascript:[result toerrorcallbackstring:callbackid]];
  12. }
  13. }
  14. @end


Inside the Nativefunction method, you first need to get a nsstring callbackid reference, which the core PhoneGap API will use to map this function response to the original JavaScript that called the function.

Next, this method uses NSLog to write the message to the Xcode Debug console, which simply indicates that it is currently executing native code.

After writing to the debug console, the function checks the resulttype passed to the function and creates the corresponding Cdvpluginresult instance. The Resulttype value is a simple string. If Resulttype is success ", the function creates success results and writes the successful callback function to the JAVASCRIPT layer using the [self writejavascript] function. Any other resulttype parameter value generates an error result, and the function writes the fault callback to the JavaScript layer.

When you write a success or error callback function back to JavaScript, always use the Cdvpluginresult instance. However, you can also use the Writejavascript function to pass any JavaScript string back to the JavaScript layer. This technology can even be used to push data from the native layer to the JavaScript layer in real time.
Calling plug-ins

Since you have created the plug-in, you can make calls from within the PHONEGAP application.

First, you need to add a reference to the new plug-in's JavaScript interface Class (Helloplugin.js). Add a new <script> tag within your index.html file:

[JavaScript]View Plaincopy
    1. <script type="Text/javascript" charset="Utf-8 " src= "Helloplugin.js" ></script>


Also after the Ondeviceready () function, add JavaScript to invoke the native plugin and process the plug-in result. Add a JavaScript function named Callnativeplugin, Nativepluginresulthandler, and Nativepluginerrorhandler as follows:

[JavaScript]View Plaincopy
  1. function Callnativeplugin (returnsuccess) {
  2. Helloplugin.callnativefunction (Nativepluginresulthandler, Nativepluginerrorhandler, returnSuccess);
  3. }
  4. function Nativepluginresulthandler (result) {
  5. Alert ("SUCCESS: \ r \ n" +result);}
  6. function Nativepluginerrorhandler (error) {
  7. Alert ("ERROR: \ r \ n" +error);
  8. }


The Callnativeplugin function simply invokes the native plug-in class interface of JavaScript. When it calls the Callnativefunction method, it passes the success and error state callback functions received from the native code layer. If the native layer succeeds in returning a callback function, the Nativepluginresulthandler function is called and the Nativepluginerrorhandler function is called when the native layer returns an error callback.

Next, add two JavaScript buttons according to the following code to invoke the plug-in.

[HTML]View Plaincopy
  1. <body>
  2. <H1>hey, it ' s cordova! </H1>
  3. <button>click to invoke the Native Plugin with an success! </button> <button>click to invoke the Native Plugin with an error! </button>
  4. </body>


Clicking the first button invokes the Callnativefunction method, generating the parameter "success". PhoneGap will then execute the native code and invoke a successful callback at the JavaScript layer (it will call the Nativepluginresulthandler function).

When you click the second button, the Callnativefunction method is called, and the parameter "error" is generated. PHONEGAP executes the native code and invokes the error callback at the JavaScript layer (it will call the Nativepluginerrorhandler function).
Mapping native code classes

At this point, you have almost everything in tandem and ready to perform, but you must also complete one more step to invoke native code in JavaScript.

You must add a mapping so that Cordova recognizes your native code class. Remember the string reference used to identify the native class when calling Cordova.exec? You need to map the string to the actual class instance in the Cordova.plist file. The Cordova.plist file contains all the configuration information for the current Cordova project.

In the Project Navigator, open the supporting Files folder, and then click the file named Cordova.plist.
Scroll down to the Plugins entry on the right and click to expand it.
Add an entry with a value of Code>com.tricedesigns.helloplugin and "Helloplugin" (see Figure 5), replacing the com.tricedesigns with your company's identity. When calling Cordova.exec, you will use this string reference to identify the native class in the third parameter.

Key is the only string reference that Phonegap.exec uses to map to native code classes. Value is the actual native class name that will be called. Save your changes.

You can now start the application and perform a thorough check.

To start the application, click the Run button or select Product > Run.

When you launch the app in IOS Simulator (or on a connected device), you'll see a simple interface with two buttons (see Figure 6). Clicking any of the buttons invokes native code for the native plug-in, and a warning message is displayed through JavaScript, whether a successful callback or an error callback is invoked.

Using native plug-ins for IOS to extend PHONEGAP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.